<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

/**
 * Makes an appointment's booking context explicit.
 *
 * The clinic used to be inferred at read time from address_id, falling back to
 * "the doctor's only clinic" when the address was missing. With per-context
 * weekly schedules that guess silently files an appointment under the wrong
 * practice, so the context is now stored on the row.
 */
final class Version20260718132000 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add appointments.clinic_id (booking context; NULL = doctor personal practice)';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE appointments ADD clinic_id INT DEFAULT NULL');
        $this->addSql('ALTER TABLE appointments ADD CONSTRAINT FK_6A41727ACC22AD4 FOREIGN KEY (clinic_id) REFERENCES clinics (id) ON DELETE SET NULL');
        $this->addSql('CREATE INDEX IDX_6A41727ACC22AD4 ON appointments (clinic_id)');

        // Backfill only where the booked address genuinely belongs to a clinic.
        // The old "doctor's only clinic" fallback is deliberately not reproduced:
        // a row without a clinic address is a personal-practice appointment, and
        // guessing here would bake the very bug this column removes into history.
        $this->addSql(<<<'SQL'
            UPDATE appointments a
            JOIN doctor_addresses da ON da.id = a.address_id
            SET a.clinic_id = da.clinic_id
            WHERE da.clinic_id IS NOT NULL
        SQL);
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE appointments DROP FOREIGN KEY FK_6A41727ACC22AD4');
        $this->addSql('DROP INDEX IDX_6A41727ACC22AD4 ON appointments');
        $this->addSql('ALTER TABLE appointments DROP clinic_id');
    }
}
