<?php

declare(strict_types=1);

namespace DoctrineMigrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Per-doctor permissions inside a clinic.
 *
 * The clinic_doctors join table is intentionally left alone; this parallel table
 * carries the permission envelope and is seeded with defaults for every doctor
 * already attached to a clinic.
 */
final class Version20260718055833 extends AbstractMigration
{
    private 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}}}';

    public function getDescription(): string
    {
        return 'Add clinic_doctor_permissions and seed existing clinic members with default permissions';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('CREATE TABLE clinic_doctor_permissions (id INT AUTO_INCREMENT NOT NULL, uuid VARCHAR(36) NOT NULL, permission JSON NOT NULL, active TINYINT NOT NULL, created_at INT NOT NULL, updated_at INT NOT NULL, clinic_id INT NOT NULL, doctor_id INT NOT NULL, UNIQUE INDEX UNIQ_2816132AD17F50A6 (uuid), INDEX IDX_2816132ACC22AD4 (clinic_id), INDEX IDX_2816132A87F4FB17 (doctor_id), UNIQUE INDEX uniq_clinic_doctor_permission (clinic_id, doctor_id), PRIMARY KEY (id)) DEFAULT CHARACTER SET utf8mb4');
        $this->addSql('ALTER TABLE clinic_doctor_permissions ADD CONSTRAINT FK_2816132ACC22AD4 FOREIGN KEY (clinic_id) REFERENCES clinics (id) ON DELETE CASCADE');
        $this->addSql('ALTER TABLE clinic_doctor_permissions ADD CONSTRAINT FK_2816132A87F4FB17 FOREIGN KEY (doctor_id) REFERENCES doctors (id) ON DELETE CASCADE');

        $this->addSql(
            'INSERT INTO clinic_doctor_permissions (uuid, clinic_id, doctor_id, permission, active, created_at, updated_at)
             SELECT UUID(), cd.clinic_id, cd.doctor_id, :permissions, 1, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()
             FROM clinic_doctors cd',
            ['permissions' => self::DEFAULT_PERMISSIONS],
        );
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE clinic_doctor_permissions DROP FOREIGN KEY FK_2816132ACC22AD4');
        $this->addSql('ALTER TABLE clinic_doctor_permissions DROP FOREIGN KEY FK_2816132A87F4FB17');
        $this->addSql('DROP TABLE clinic_doctor_permissions');
    }
}
