<?php

namespace App\Insurance\Entity;

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

/**
 * Which kinds of service a doctor/clinic covers with insurance at all. This is a
 * tenant-wide switch shared by every insurance of that tenant — not a per-insurance
 * setting. A missing row reads as enabled, so tenants created before this setting
 * keep both kinds available.
 */
#[ORM\Entity(repositoryClass: TenantServiceCategorySettingRepository::class)]
#[ORM\Table(name: 'tenant_service_category_settings')]
#[ORM\UniqueConstraint(name: 'uniq_tenant_service_category_setting', columns: ['entity_type', 'entity_id', 'service_category'])]
class TenantServiceCategorySetting
{
    public const TYPE_DOCTOR = 'doctor';
    public const TYPE_CLINIC = 'clinic';

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

    #[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: 'service_category', type: 'string', length: 30, enumType: ServiceCategory::class)]
    private ServiceCategory $serviceCategory;

    #[ORM\Column(type: 'boolean', options: ['default' => true])]
    private bool $enabled = true;

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

    public function __construct(string $entityType, int $entityId, ServiceCategory $serviceCategory, bool $enabled = true)
    {
        $this->entityType      = $entityType;
        $this->entityId        = $entityId;
        $this->serviceCategory = $serviceCategory;
        $this->enabled         = $enabled;
        $this->updatedAt       = time();
    }

    public function getId(): ?int                          { return $this->id; }
    public function getEntityType(): string                { return $this->entityType; }
    public function getEntityId(): int                     { return $this->entityId; }
    public function getServiceCategory(): ServiceCategory  { return $this->serviceCategory; }
    public function isEnabled(): bool                      { return $this->enabled; }

    public function setEnabled(bool $v): self
    {
        $this->enabled   = $v;
        $this->updatedAt = time();
        return $this;
    }

    public function toArray(): array
    {
        return [
            'key'     => $this->serviceCategory->value,
            'label'   => $this->serviceCategory->label(),
            'enabled' => $this->enabled,
        ];
    }
}
