<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

final class Version20260302103003 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Create comments table + make piece reference unique instead of name';
    }

    public function up(Schema $schema): void
    {
        // Comments table (IF NOT EXISTS in case first attempt partially succeeded)
        $this->addSql('CREATE TABLE IF NOT EXISTS comments (id VARCHAR(36) NOT NULL, content TEXT NOT NULL, entity_type VARCHAR(50) NOT NULL, entity_id VARCHAR(36) NOT NULL, entity_name VARCHAR(255) DEFAULT NULL, author_id VARCHAR(36) NOT NULL, author_name VARCHAR(255) NOT NULL, status VARCHAR(20) NOT NULL, resolved_by_id VARCHAR(36) DEFAULT NULL, resolved_by_name VARCHAR(255) DEFAULT NULL, resolved_at TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT NULL, created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, updated_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, PRIMARY KEY (id))');
        $this->addSql('CREATE INDEX IF NOT EXISTS idx_comment_entity_status ON comments (entity_type, entity_id, status)');
        $this->addSql('COMMENT ON COLUMN comments.resolved_at IS \'(DC2Type:datetime_immutable)\'');
        $this->addSql('COMMENT ON COLUMN comments.created_at IS \'(DC2Type:datetime_immutable)\'');
        $this->addSql('COMMENT ON COLUMN comments.updated_at IS \'(DC2Type:datetime_immutable)\'');

        // Piece: remove unique constraint on name (it's a constraint, not just an index)
        $this->addSql('ALTER TABLE pieces DROP CONSTRAINT IF EXISTS uniq_b92d74725e237e06');

        // Deduplicate piece references before adding unique constraint
        $this->addSql("
            UPDATE pieces p
            SET reference = p.reference || '-' || LEFT(p.id, 6)
            FROM (
                SELECT id, reference,
                       ROW_NUMBER() OVER (PARTITION BY reference ORDER BY createdat) AS rn
                FROM pieces
                WHERE reference IS NOT NULL AND reference != ''
            ) dup
            WHERE p.id = dup.id AND dup.rn > 1
        ");

        $this->addSql('CREATE UNIQUE INDEX IF NOT EXISTS uniq_pieces_reference ON pieces (reference)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('DROP TABLE IF EXISTS comments');
        $this->addSql('DROP INDEX IF EXISTS uniq_pieces_reference');
        $this->addSql('CREATE UNIQUE INDEX uniq_b92d74725e237e06 ON pieces (name)');
    }
}
