<?php

namespace App\Clinic\Entity;

use App\Clinic\Repository\ClinicDoctorPermissionRepository;
use App\Doctor\Entity\Doctor;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;

/**
 * سطح دسترسی یک پزشکِ عضو در یک کلینیک مشخص.
 *
 * جدول join «clinic_doctors» عمداً دست‌نخورده می‌ماند (شش نقطه در کد به ManyToMany
 * آن وابسته‌اند)؛ این جدول موازی فقط مجوزها را نگه می‌دارد.
 */
#[ORM\Entity(repositoryClass: ClinicDoctorPermissionRepository::class)]
#[ORM\Table(name: 'clinic_doctor_permissions')]
#[ORM\UniqueConstraint(name: 'uniq_clinic_doctor_permission', columns: ['clinic_id', 'doctor_id'])]
class ClinicDoctorPermission
{
    public const DEFAULT_PERMISSIONS = [
        'version'   => 1,
        'resources' => [
            'appointments'         => ['view' => true,  'create' => true,  'cancel' => true,  'update_status' => true],
            'appointment_settings' => ['view' => true,  'update' => true],
            'patients'             => ['view' => true,  'create' => true,  'update' => true,  'delete' => false],
            'payments'             => ['view' => true,  'create' => false, 'update' => false, 'delete' => false],
            'services'             => ['view' => true,  'update' => false],
            'clinic_info'          => ['view' => true,  'update' => false],
            'insurances'           => ['view' => true,  'create' => false, 'update' => false, 'delete' => false],
            'addresses'            => ['view' => true,  'create' => false, 'update' => false, 'delete' => false],
            'inventory'            => ['view' => false, 'create' => false, 'update' => false, 'delete' => false],
            'tags'                 => ['view' => false, 'create' => false, 'update' => false, 'delete' => false],
            'staff'                => ['view' => false, 'create' => false, 'update' => false, 'delete' => false],
            'discounts'            => ['view' => false, 'create' => false, 'update' => false, 'delete' => false],
            'sms'                  => ['view' => false, 'create' => false, 'update' => false, 'delete' => false],
        ],
    ];

    #[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: Clinic::class)]
    #[ORM\JoinColumn(name: 'clinic_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
    private Clinic $clinic;

    #[ORM\ManyToOne(targetEntity: Doctor::class)]
    #[ORM\JoinColumn(name: 'doctor_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
    private Doctor $doctor;

    #[ORM\Column(name: 'permission', type: 'json')]
    private array $permissions;

    #[ORM\Column(type: 'boolean')]
    private bool $active = true;

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

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

    public function __construct(Clinic $clinic, Doctor $doctor)
    {
        $this->uuid        = Uuid::v4()->toRfc4122();
        $this->clinic      = $clinic;
        $this->doctor      = $doctor;
        $this->permissions = self::DEFAULT_PERMISSIONS;
        $this->createdAt   = time();
        $this->updatedAt   = time();
    }

    public function getId(): ?int           { return $this->id; }
    public function getUuid(): string       { return $this->uuid; }
    public function getClinic(): Clinic     { return $this->clinic; }
    public function getDoctor(): Doctor     { return $this->doctor; }
    public function getPermissions(): array { return $this->permissions; }
    public function isActive(): bool        { return $this->active; }
    public function getCreatedAt(): int     { return $this->createdAt; }
    public function getUpdatedAt(): int     { return $this->updatedAt; }

    public function setActive(bool $v): self { $this->active = $v; $this->touch(); return $this; }

    public function can(string $resource, string $action): bool
    {
        if (!$this->active) {
            return false;
        }

        return (bool) ($this->permissions['resources'][$resource][$action] ?? false);
    }

    /** ادغام عمقی — فقط منابع/اکشن‌هایی که ارسال شده‌اند تغییر می‌کنند. */
    public function mergePermissions(array $patch): void
    {
        $current  = $this->permissions;
        $resources = $patch['resources'] ?? $patch;

        foreach ($resources as $resource => $actions) {
            if (!is_array($actions) || !isset(self::DEFAULT_PERMISSIONS['resources'][$resource])) {
                continue;
            }
            foreach ($actions as $action => $value) {
                if (!array_key_exists($action, self::DEFAULT_PERMISSIONS['resources'][$resource])) {
                    continue;
                }
                $current['resources'][$resource][$action] = (bool) $value;
            }
        }

        $this->permissions = $current;
        $this->touch();
    }

    private function touch(): void { $this->updatedAt = time(); }

    /**
     * envelope کامل برگردانده می‌شود (نه flatten) تا کلاینت همه‌جا با یک شکل واحد
     * روبه‌رو باشد — برخلاف DoctorSecretary::toArray که آن را تخت می‌کند.
     */
    public function toArray(): array
    {
        return [
            'uuid'        => $this->uuid,
            'clinic_uuid' => $this->clinic->getUuid(),
            'doctor_uuid' => $this->doctor->getUuid(),
            'doctor_name' => $this->doctor->getName(),
            'active'      => $this->active,
            'permissions' => $this->permissions,
            'created_at'  => $this->createdAt,
            'updated_at'  => $this->updatedAt,
        ];
    }
}
