<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

final class Version20260519175142 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Attach existing projects to Standard workflow (NOT NULL, RESTRICT)';
    }

    public function up(Schema $schema): void
    {
        $standardId = $this->connection->fetchOne("SELECT id FROM workflow WHERE name = 'Standard'");
        if (!$standardId) {
            throw new MigrationException('Workflow Standard introuvable.');
        }

        $this->addSql('ALTER TABLE project ADD COLUMN workflow_id INT DEFAULT NULL');
        $this->addSql("UPDATE project SET workflow_id = {$standardId}");
        $this->addSql('ALTER TABLE project ALTER COLUMN workflow_id SET NOT NULL');
        $this->addSql('ALTER TABLE project ADD CONSTRAINT FK_project_workflow FOREIGN KEY (workflow_id) REFERENCES workflow (id) ON DELETE RESTRICT NOT DEFERRABLE');
        $this->addSql('CREATE INDEX IDX_project_workflow ON project (workflow_id)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE project DROP CONSTRAINT FK_project_workflow');
        $this->addSql('DROP INDEX IDX_project_workflow');
        $this->addSql('ALTER TABLE project DROP COLUMN workflow_id');
    }
}
