<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

final class Version20260430120000 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add tenant domains and configure Daroul-Ilm canonical and alias hosts';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('CREATE TABLE tenant_domains (id INT AUTO_INCREMENT NOT NULL, ecole_id INT NOT NULL, host VARCHAR(255) NOT NULL, canonical TINYINT DEFAULT 0 NOT NULL, active TINYINT DEFAULT 1 NOT NULL, created_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', updated_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', UNIQUE INDEX UNIQ_7A11E337604B8382 (host), INDEX IDX_7A11E33777EF1B1E (ecole_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4');
        $this->addSql('ALTER TABLE tenant_domains ADD CONSTRAINT FK_7A11E33777EF1B1E FOREIGN KEY (ecole_id) REFERENCES ecoles (id) ON DELETE CASCADE');

        $this->addSql("UPDATE ecoles SET sous_domaine = 'darulilm' WHERE slug = 'daroul-ilm'");
        $this->addSql("INSERT INTO tenant_domains (ecole_id, host, canonical, active, created_at, updated_at) SELECT id, CONCAT(sous_domaine, '.salsabil.cm'), 1, active, NOW(), NOW() FROM ecoles WHERE sous_domaine IS NOT NULL AND sous_domaine <> ''");
        $this->addSql("INSERT INTO tenant_domains (ecole_id, host, canonical, active, created_at, updated_at) SELECT id, 'daroulilm.salsabil.cm', 0, 1, NOW(), NOW() FROM ecoles WHERE slug = 'daroul-ilm'");
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE tenant_domains DROP FOREIGN KEY FK_7A11E33777EF1B1E');
        $this->addSql('DROP TABLE tenant_domains');
        $this->addSql("UPDATE ecoles SET sous_domaine = 'daroulilm' WHERE slug = 'daroul-ilm'");
    }
}
