<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

final class Version20260519175114 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Attach existing TaskStatus rows to Standard workflow and backfill category (strict mapping)';
    }

    public function up(Schema $schema): void
    {
        // 1) Récupérer l'id du workflow Standard
        $standardId = $this->connection->fetchOne("SELECT id FROM workflow WHERE name = 'Standard'");
        if (!$standardId) {
            throw new MigrationException('Workflow Standard introuvable. Lancer M1 d\'abord.');
        }

        // 2) Garde-fou : vérifier qu'il n'y a pas de label hors mapping
        $mapping = [
            'A faire'                  => 'todo',
            'À faire'                  => 'todo',
            'En cours'                 => 'in_progress',
            'Bloqué'                   => 'blocked',
            'En attente de validation' => 'review',
            'Terminé'                  => 'done',
        ];
        $rows = $this->connection->fetchAllAssociative('SELECT id, label FROM task_status');
        foreach ($rows as $row) {
            if (!isset($mapping[$row['label']])) {
                throw new MigrationException(sprintf(
                    'TaskStatus #%d ("%s") n\'est pas mappable. Ajoutez son mapping dans la migration avant de relancer.',
                    $row['id'],
                    $row['label'],
                ));
            }
        }

        // 3) Ajouter colonnes nullable
        $this->addSql('ALTER TABLE task_status ADD COLUMN workflow_id INT DEFAULT NULL');
        $this->addSql('ALTER TABLE task_status ADD COLUMN category VARCHAR(32) DEFAULT NULL');

        // 4) Backfill
        $this->addSql("UPDATE task_status SET workflow_id = {$standardId}");
        foreach ($mapping as $label => $cat) {
            $this->addSql(sprintf(
                "UPDATE task_status SET category = '%s' WHERE label = '%s'",
                $cat,
                str_replace("'", "''", $label),
            ));
        }

        // 5) NOT NULL + FK
        $this->addSql('ALTER TABLE task_status ALTER COLUMN workflow_id SET NOT NULL');
        $this->addSql('ALTER TABLE task_status ALTER COLUMN category SET NOT NULL');
        $this->addSql('ALTER TABLE task_status ADD CONSTRAINT FK_task_status_workflow FOREIGN KEY (workflow_id) REFERENCES workflow (id) ON DELETE CASCADE NOT DEFERRABLE');
        $this->addSql('CREATE INDEX IDX_task_status_workflow ON task_status (workflow_id)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE task_status DROP CONSTRAINT FK_task_status_workflow');
        $this->addSql('DROP INDEX IDX_task_status_workflow');
        $this->addSql('ALTER TABLE task_status DROP COLUMN workflow_id');
        $this->addSql('ALTER TABLE task_status DROP COLUMN category');
    }
}
