<?php

namespace App\Insurance\Entity;

use App\Insurance\Enum\ServiceCategory;
use App\Insurance\Repository\InsuranceCoverageDefaultRepository;
use Doctrine\ORM\Mapping as ORM;

/**
 * Central (admin-managed) coverage percentage of an insurance per service category.
 * Single source of truth: tenant contracts fall back to these values live, so a
 * change here immediately applies to every doctor/clinic that has not overridden it.
 */
#[ORM\Entity(repositoryClass: InsuranceCoverageDefaultRepository::class)]
#[ORM\Table(name: 'insurance_coverage_defaults')]
#[ORM\UniqueConstraint(name: 'uniq_insurance_service_category', columns: ['insurance_id', 'service_category'])]
class InsuranceCoverageDefault
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id = null;

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

    #[ORM\Column(name: 'service_category', type: 'string', length: 30, enumType: ServiceCategory::class)]
    private ServiceCategory $serviceCategory;

    #[ORM\Column(name: 'coverage_percent', type: 'decimal', precision: 5, scale: 2)]
    private string $coveragePercent = '0.00';

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

    public function __construct(int $insuranceId, ServiceCategory $serviceCategory, float $coveragePercent = 0.0)
    {
        $this->insuranceId     = $insuranceId;
        $this->serviceCategory = $serviceCategory;
        $this->coveragePercent = (string) $coveragePercent;
        $this->updatedAt       = time();
    }

    public function getId(): ?int                        { return $this->id; }
    public function getInsuranceId(): int                { return $this->insuranceId; }
    public function getServiceCategory(): ServiceCategory { return $this->serviceCategory; }
    public function getCoveragePercent(): float          { return (float) $this->coveragePercent; }

    public function setCoveragePercent(float $v): self
    {
        $this->coveragePercent = (string) $v;
        $this->updatedAt       = time();
        return $this;
    }

    public function toArray(): array
    {
        return [
            'insurance_id'     => $this->insuranceId,
            'service_category' => $this->serviceCategory->value,
            'label'            => $this->serviceCategory->label(),
            'coverage_percent' => (float) $this->coveragePercent,
        ];
    }
}
