<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

/**
 * Phase 3 of the tenant-marking series: user_active_context stored only a
 * db_uuid, which forced every environment lookup to try clinics first and fall
 * back to doctors. db_type records which of the two the uuid addresses.
 *
 * Backfilled by matching the uuid against both tables. Rows whose uuid no longer
 * resolves are deleted rather than guessed: this table is a cache of "the last
 * environment the user picked", and losing a row simply sends the resolver back
 * to its role fallback — the same state a brand-new user is in. This is the only
 * migration in the series allowed to delete rows.
 */
final class Version20260728080955 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Record whether user_active_context.db_uuid points at a doctor or a clinic';
    }

    public function up(Schema $schema): void
    {
        $this->connection->executeStatement(
            'ALTER TABLE user_active_context ADD db_type VARCHAR(10) NULL'
        );

        $this->connection->executeStatement(
            "UPDATE user_active_context uac JOIN clinics c ON c.uuid = uac.db_uuid SET uac.db_type = 'clinic'"
        );
        $this->connection->executeStatement(
            "UPDATE user_active_context uac JOIN doctors d ON d.uuid = uac.db_uuid
             SET uac.db_type = 'doctor' WHERE uac.db_type IS NULL"
        );

        $orphans = (int) $this->connection->executeStatement(
            'DELETE FROM user_active_context WHERE db_type IS NULL'
        );
        if ($orphans > 0) {
            $this->write("Dropped {$orphans} active-context rows whose db_uuid no longer resolves.");
        }

        $this->connection->executeStatement(
            'ALTER TABLE user_active_context MODIFY db_type VARCHAR(10) NOT NULL'
        );
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE user_active_context DROP db_type');
    }

    /** DDL on MariaDB commits implicitly; wrapping up() in a transaction would be a lie. */
    public function isTransactional(): bool
    {
        return false;
    }
}
