<?php

namespace App\Entity;

use App\Repository\AuditLogRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: AuditLogRepository::class)]
class AuditLog
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\ManyToOne(targetEntity: Account::class, inversedBy: 'auditLogs')]
    #[ORM\JoinColumn(nullable: false)]
    private ?Account $account = null;

    #[ORM\Column]
    private \DateTimeImmutable $actionAt;

    #[ORM\Column(length: 50)]
    private ?string $type = null;

    #[ORM\Column(type: Types::TEXT)]
    private ?string $message = null;

    #[ORM\Column(length: 255)]
    private ?string $path = null;
    #[ORM\Column(length: 255)]
    private ?string $userAgent = null;

    #[ORM\Column(length: 64)]
    private ?string $hashCode = null;

    // Le constructeur force le remplissage des données dès le départ
    public function __construct(Account $account, string $type, string $message, string $path,string $userAgent)
    {
        $this->account = $account;
        $this->type = $type;
        $this->message = $message;
        $this->path = $path;
        $this->actionAt = new \DateTimeImmutable();
        $this->userAgent = $userAgent;
        $this->hashCode = $this->generateSignature();
    }

    public function generateSignature(): string
    {
        $data = sprintf(
            '%s|%s|%s|%s|%s|%s',
            $this->account->getEmail(), // L'email est plus fiable que l'ID si l'user est nouveau
            $this->type,
            $this->message,
            $this->path,
            $this->actionAt->format('Y-m-d H:i:s'),
            $_ENV['APP_SECRET'] ?? 'default_secret'
        );

        return hash('sha256', $data);
    }

    // Uniquement des Getters (Pas de Setters = Pas de modification possible en PHP)
    public function getId(): ?int { return $this->id; }
    public function getAccount(): ?Account { return $this->account; }
    public function getActionAt(): \DateTimeImmutable { return $this->actionAt; }
    public function getType(): ?string { return $this->type; }
    public function getMessage(): ?string { return $this->message; }
    public function getPath(): ?string { return $this->path; }
    public function getUserAgent(): ?string{ return $this->userAgent;}
    public function getHashCode(): ?string{ return $this->hashCode;}
}
