<?php

namespace App\Billing\Entity;

use App\Billing\Repository\ClaimRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;

#[ORM\Entity(repositoryClass: ClaimRepository::class)]
#[ORM\Table(name: 'claims')]
#[ORM\Index(columns: ['entity_type', 'entity_id'], name: 'idx_claim_tenant')]
#[ORM\Index(columns: ['insurance_id', 'status'], name: 'idx_claim_insurance_status')]
class Claim
{
    public const STATUS_PENDING   = 'pending';
    public const STATUS_SUBMITTED = 'submitted';
    public const STATUS_APPROVED  = 'approved';
    public const STATUS_REJECTED  = 'rejected';
    public const STATUS_PAID      = 'paid';

    public const KIND_BASE          = 'base';
    public const KIND_SUPPLEMENTARY = 'supplementary';

    private const TRANSITIONS = [
        self::STATUS_PENDING   => [self::STATUS_SUBMITTED],
        self::STATUS_SUBMITTED => [self::STATUS_APPROVED, self::STATUS_REJECTED],
        self::STATUS_APPROVED  => [self::STATUS_PAID],
        self::STATUS_REJECTED  => [],
        self::STATUS_PAID      => [],
    ];

    #[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: 'entity_type', type: 'string', length: 10)]
    private string $entityType;

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

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

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

    #[ORM\Column(name: 'total_claimed_rials', type: 'integer')]
    private int $totalClaimedRials = 0;

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

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

    #[ORM\Column(type: 'string', length: 15)]
    private string $status = self::STATUS_PENDING;

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

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

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

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

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

    #[ORM\OneToMany(targetEntity: ClaimItem::class, mappedBy: 'claim', cascade: ['persist', 'remove'], orphanRemoval: true)]
    private Collection $items;

    public function __construct(string $entityType, int $entityId, int $insuranceId, string $insuranceKind)
    {
        $this->uuid          = Uuid::v4()->toRfc4122();
        $this->entityType    = $entityType;
        $this->entityId      = $entityId;
        $this->insuranceId   = $insuranceId;
        $this->insuranceKind = $insuranceKind;
        $this->createdAt     = time();
        $this->updatedAt     = time();
        $this->items         = new ArrayCollection();
    }

    public function getId(): ?int           { return $this->id; }
    public function getUuid(): string       { return $this->uuid; }
    public function getEntityType(): string { return $this->entityType; }
    public function getEntityId(): int      { return $this->entityId; }
    public function getInsuranceId(): int   { return $this->insuranceId; }
    public function getInsuranceKind(): string { return $this->insuranceKind; }
    public function getStatus(): string     { return $this->status; }
    public function getTotalClaimedRials(): int { return $this->totalClaimedRials; }
    public function getTotalApprovedRials(): ?int { return $this->totalApprovedRials; }
    public function getTotalPaidRials(): ?int { return $this->totalPaidRials; }
    /** @return Collection<int, ClaimItem> */
    public function getItems(): Collection  { return $this->items; }

    public function addItem(ClaimItem $item): self
    {
        $this->items->add($item);
        $this->totalClaimedRials += $item->getClaimedRials();
        $this->updatedAt = time();
        return $this;
    }

    public function canTransitionTo(string $status): bool
    {
        return in_array($status, self::TRANSITIONS[$this->status] ?? [], true);
    }

    public function submit(): void
    {
        $this->status      = self::STATUS_SUBMITTED;
        $this->submittedAt = time();
        $this->updatedAt   = time();
    }

    public function approve(?int $approvedRials = null): void
    {
        $this->status             = self::STATUS_APPROVED;
        $this->totalApprovedRials = $approvedRials ?? $this->totalClaimedRials;
        $this->updatedAt          = time();
    }

    public function reject(string $reason): void
    {
        $this->status       = self::STATUS_REJECTED;
        $this->rejectReason = $reason;
        $this->settledAt    = time();
        $this->updatedAt    = time();
    }

    public function pay(?int $paidRials = null): void
    {
        $this->status         = self::STATUS_PAID;
        $this->totalPaidRials = $paidRials ?? $this->totalApprovedRials ?? $this->totalClaimedRials;
        $this->settledAt      = time();
        $this->updatedAt      = time();
    }

    public function toArray(): array
    {
        return [
            'uuid'                 => $this->uuid,
            'entity_type'          => $this->entityType,
            'entity_id'            => $this->entityId,
            'insurance_id'         => $this->insuranceId,
            'insurance_kind'       => $this->insuranceKind,
            'total_claimed_rials'  => $this->totalClaimedRials,
            'total_approved_rials' => $this->totalApprovedRials,
            'total_paid_rials'     => $this->totalPaidRials,
            'status'               => $this->status,
            'reject_reason'        => $this->rejectReason,
            'submitted_at'         => $this->submittedAt,
            'settled_at'           => $this->settledAt,
            'created_at'           => $this->createdAt,
            'items'                => array_map(fn(ClaimItem $i) => $i->toArray(), $this->items->toArray()),
        ];
    }
}
