<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

final class Version20260225000200 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Fix schema drift (indexes, FK, longtext nullability)';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE knowledge_tag CHANGE description description LONGTEXT DEFAULT NULL');

        if ($this->indexExists('knowledge_tag', 'uniq_knowledge_tag_slug')) {
            $this->addSql(
                'ALTER TABLE knowledge_tag RENAME INDEX uniq_knowledge_tag_slug TO UNIQ_86B46255989D9B62'
            );
        }

        $this->addSql('ALTER TABLE document DROP FOREIGN KEY FK_D8698A769407EE77');
        $this->addSql('ALTER TABLE document ADD CONSTRAINT FK_D8698A769407EE77 FOREIGN KEY (current_version_id) REFERENCES document_version (id)');

        $this->addSql('ALTER TABLE tag_rebuild_job CHANGE error_message error_message LONGTEXT DEFAULT NULL');

        if ($this->indexExists('document_tag', 'idx_document_tag_document')) {
            $this->addSql(
                'ALTER TABLE document_tag RENAME INDEX idx_document_tag_document TO IDX_D0234567C33F7837'
            );
        }

        if ($this->indexExists('document_tag', 'idx_document_tag_tag')) {
            $this->addSql(
                'ALTER TABLE document_tag RENAME INDEX idx_document_tag_tag TO IDX_D0234567BAD26311'
            );
        }
    }

    private function indexExists(string $table, string $index): bool
    {
        $count = (int) $this->connection->fetchOne(
            <<<SQL
            SELECT COUNT(*)
            FROM INFORMATION_SCHEMA.STATISTICS
            WHERE TABLE_SCHEMA = DATABASE()
              AND TABLE_NAME = :table
              AND INDEX_NAME = :index
            SQL,
            [
                'table' => $table,
                'index' => $index,
            ]
        );

        return $count > 0;
    }

    public function down(Schema $schema): void
    {
    }
}