<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

final class Version20260527140000 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Machine name uniqueness is now scoped per site: drop global unique index on machines(name), add composite unique index on (name, siteid)';
    }

    public function up(Schema $schema): void
    {
        // Drop the global unique index/constraint on machines(name).
        // Doctrine-generated name (CRC32 of table+column): uniq_f1ce8ded5e237e06.
        // It may exist either as a constraint or as a bare index depending on origin,
        // so we drop defensively in both forms.
        $this->addSql('ALTER TABLE machines DROP CONSTRAINT IF EXISTS uniq_f1ce8ded5e237e06');
        $this->addSql('DROP INDEX IF EXISTS uniq_f1ce8ded5e237e06');
        // Defensive fallbacks for other possible legacy names of the global unique index on name.
        $this->addSql('ALTER TABLE machines DROP CONSTRAINT IF EXISTS machines_name_key');
        $this->addSql('DROP INDEX IF EXISTS machines_name_key');

        // New uniqueness scope: a machine name is unique within a given site only.
        $this->addSql('CREATE UNIQUE INDEX IF NOT EXISTS uniq_machine_name_site ON machines (name, siteid)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('DROP INDEX IF EXISTS uniq_machine_name_site');

        // Best-effort restore of the global unique index on machines(name).
        // WARNING: this will fail if duplicate names now exist across sites (which the
        // per-site scope allowed). Resolve duplicates manually before rolling back.
        $this->addSql('CREATE UNIQUE INDEX IF NOT EXISTS uniq_f1ce8ded5e237e06 ON machines (name)');
    }
}
