<?php

namespace App\ClinicService\Entity;

use App\ClinicService\Repository\ServiceItemAuditLogRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;

/**
 * تاریخچه‌ی تغییرات یک خدمت: چه کسی، چه فیلدی را، کِی و از چه مقداری به چه مقداری
 * تغییر داد. هم‌شکل {@see \App\Patient\Entity\SessionAuditLog} است تا الگوی لاگ در
 * سراسر پروژه یکسان بماند.
 */
#[ORM\Entity(repositoryClass: ServiceItemAuditLogRepository::class)]
#[ORM\Table(name: 'service_item_audit_logs')]
#[ORM\Index(columns: ['service_item_id', 'created_at'], name: 'idx_service_item_audit_item')]
class ServiceItemAuditLog
{
    public const OP_CREATE = 'create';
    public const OP_UPDATE = 'update';

    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id = null;

    #[ORM\Column(type: 'string', length: 36, unique: true)]
    private string $uuid;

    #[ORM\ManyToOne(targetEntity: ServiceItem::class)]
    #[ORM\JoinColumn(name: 'service_item_id', nullable: false, onDelete: 'CASCADE')]
    private ServiceItem $serviceItem;

    #[ORM\Column(type: 'string', length: 40)]
    private string $field;

    #[ORM\Column(type: 'string', length: 10)]
    private string $operation;

    #[ORM\Column(name: 'old_value', type: 'text', nullable: true)]
    private ?string $oldValue = null;

    #[ORM\Column(name: 'new_value', type: 'text', nullable: true)]
    private ?string $newValue = null;

    #[ORM\Column(name: 'actor_user_id', type: 'integer', nullable: true)]
    private ?int $actorUserId = null;

    #[ORM\Column(name: 'actor_name', type: 'string', length: 191, nullable: true)]
    private ?string $actorName = null;

    #[ORM\Column(name: 'created_at', type: 'integer')]
    private int $createdAt;

    public function __construct(ServiceItem $serviceItem, string $field, string $operation)
    {
        $this->uuid        = Uuid::v4()->toRfc4122();
        $this->serviceItem = $serviceItem;
        $this->field       = $field;
        $this->operation   = $operation;
        $this->createdAt   = time();
    }

    public function setActor(?int $userId, ?string $name): self { $this->actorUserId = $userId; $this->actorName = $name; return $this; }
    public function setValues(?string $old, ?string $new): self { $this->oldValue = $old; $this->newValue = $new; return $this; }

    public function getUuid(): string { return $this->uuid; }

    public function toArray(): array
    {
        return [
            'uuid'       => $this->uuid,
            'field'      => $this->field,
            'operation'  => $this->operation,
            'old_value'  => $this->oldValue,
            'new_value'  => $this->newValue,
            'actor_name' => $this->actorName,
            'created_at' => $this->createdAt,
        ];
    }
}
