<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20260709033925 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Representation multi-city (representation_cities) + domain + is_global; backfills from legacy representations.city_id and cities.representation_id';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('CREATE TABLE representation_cities (representation_id INT NOT NULL, city_id INT NOT NULL, INDEX IDX_2BE110B046CE82F4 (representation_id), INDEX IDX_2BE110B08BAC62AF (city_id), PRIMARY KEY (representation_id, city_id)) DEFAULT CHARACTER SET utf8mb4');
        $this->addSql('ALTER TABLE representation_cities ADD CONSTRAINT FK_2BE110B046CE82F4 FOREIGN KEY (representation_id) REFERENCES representations (id) ON DELETE CASCADE');
        $this->addSql('ALTER TABLE representation_cities ADD CONSTRAINT FK_2BE110B08BAC62AF FOREIGN KEY (city_id) REFERENCES cities (id) ON DELETE CASCADE');
        $this->addSql('ALTER TABLE representations ADD domain VARCHAR(255) DEFAULT NULL, ADD is_global TINYINT NOT NULL DEFAULT 0');
        $this->addSql('CREATE UNIQUE INDEX UNIQ_C90A401A7A91E0B ON representations (domain)');

        // Backfill from both legacy single-city mappings; idempotent and only for still-existing cities.
        $this->addSql('INSERT IGNORE INTO representation_cities (representation_id, city_id)
            SELECT r.id, r.city_id FROM representations r JOIN cities c ON c.id = r.city_id');
        $this->addSql('INSERT IGNORE INTO representation_cities (representation_id, city_id)
            SELECT c.representation_id, c.id FROM cities c JOIN representations r ON r.id = c.representation_id');
    }

    public function down(Schema $schema): void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->addSql('ALTER TABLE representation_cities DROP FOREIGN KEY FK_2BE110B046CE82F4');
        $this->addSql('ALTER TABLE representation_cities DROP FOREIGN KEY FK_2BE110B08BAC62AF');
        $this->addSql('DROP TABLE representation_cities');
        $this->addSql('DROP INDEX UNIQ_C90A401A7A91E0B ON representations');
        $this->addSql('ALTER TABLE representations DROP domain, DROP is_global');
    }
}
