<?php

namespace App\Billing\Entity;

use App\Billing\Repository\ClaimStatusLogRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;

/**
 * تاریخچه‌ی تغییر وضعیت یک مطالبه.
 *
 * وضعیت روی خودِ Claim فقط «آخرین حالت» است؛ پیگیری پرونده‌ی بیمه نیاز دارد بداند
 * چه کسی، کِی و با چه توضیحی آن را جابه‌جا کرده است.
 */
#[ORM\Entity(repositoryClass: ClaimStatusLogRepository::class)]
#[ORM\Table(name: 'claim_status_logs')]
#[ORM\Index(columns: ['claim_id'], name: 'idx_claim_status_log_claim')]
class ClaimStatusLog
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id = null;

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

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

    /** null فقط برای ردیف ساخت اولیه. */
    #[ORM\Column(name: 'from_status', type: 'string', length: 15, nullable: true)]
    private ?string $fromStatus = null;

    #[ORM\Column(name: 'to_status', type: 'string', length: 15)]
    private string $toStatus;

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

    /** null یعنی سیستمی (backfill یا اتوماسیون). */
    #[ORM\Column(name: 'created_by_id', type: 'integer', nullable: true)]
    private ?int $createdById = null;

    #[ORM\Column(name: 'created_by_name', type: 'string', length: 120, nullable: true)]
    private ?string $createdByName = null;

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

    public function __construct(int $claimId, ?string $fromStatus, string $toStatus)
    {
        $this->uuid       = Uuid::v4()->toRfc4122();
        $this->claimId    = $claimId;
        $this->fromStatus = $fromStatus;
        $this->toStatus   = $toStatus;
        $this->createdAt  = time();
    }

    public function getId(): ?int          { return $this->id; }
    public function getClaimId(): int      { return $this->claimId; }
    public function getToStatus(): string  { return $this->toStatus; }

    public function setNote(?string $note): self
    {
        $this->note = $note !== null && trim($note) !== '' ? trim($note) : null;
        return $this;
    }

    public function setActor(?int $userId, ?string $name): self
    {
        $this->createdById   = $userId;
        $this->createdByName = $name;
        return $this;
    }

    public function setCreatedAt(int $at): self
    {
        $this->createdAt = $at;
        return $this;
    }

    public function toArray(): array
    {
        return [
            'uuid'        => $this->uuid,
            'from_status' => $this->fromStatus,
            'to_status'   => $this->toStatus,
            'note'        => $this->note,
            'by'          => $this->createdByName,
            'at'          => $this->createdAt,
        ];
    }
}
