<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Doctrine\Migrations;

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

final class Version20260415091000 extends AbstractMigration
{
    private const array EXPECTED_COLUMNS = [
        'id',
        'email',
        'imported_group_name',
        'resolved_group_name',
        'created_at',
        'updated_at',
    ];

    public function getDescription(): string
    {
        return 'Create client email group mapping table for Excel imports.';
    }

    public function up(Schema $schema): void
    {
        if ($this->tableExists()) {
            $this->repairExistingTable();

            return;
        }

        $table = $schema->createTable('client_email_group_mapping');
        $table->addColumn('id', 'integer', ['autoincrement' => true]);
        $table->addColumn('email', 'string', ['length' => 180]);
        $table->addColumn('imported_group_name', 'string', ['length' => 255]);
        $table->addColumn('resolved_group_name', 'string', ['length' => 255, 'notnull' => false]);
        $table->addColumn('created_at', 'datetime_immutable');
        $table->addColumn('updated_at', 'datetime_immutable');
        $table->setPrimaryKey(['id']);
        $table->addUniqueIndex(['email'], 'uniq_client_email_group_mapping_email');
    }

    public function down(Schema $schema): void
    {
        if ($schema->hasTable('client_email_group_mapping')) {
            $schema->dropTable('client_email_group_mapping');
        }
    }

    private function tableExists(): bool
    {
        return (bool) $this->connection->fetchOne(
            "SELECT to_regclass('public.client_email_group_mapping') IS NOT NULL"
        );
    }

    private function repairExistingTable(): void
    {
        $columns = $this->connection->fetchFirstColumn(<<<'SQL'
            SELECT column_name
            FROM information_schema.columns
            WHERE table_schema = 'public'
              AND table_name = 'client_email_group_mapping'
            SQL);
        $missingColumns = array_values(array_diff(self::EXPECTED_COLUMNS, $columns));

        $this->abortIf(
            [] !== $missingColumns,
            \sprintf(
                'The existing client_email_group_mapping table is missing columns: %s.',
                implode(', ', $missingColumns),
            ),
        );

        $this->addSql('CREATE SEQUENCE IF NOT EXISTS client_email_group_mapping_id_seq');
        $this->addSql('ALTER SEQUENCE client_email_group_mapping_id_seq OWNED BY client_email_group_mapping.id');
        $this->addSql("ALTER TABLE client_email_group_mapping ALTER COLUMN id SET DEFAULT nextval('client_email_group_mapping_id_seq'::regclass)");
        $this->addSql(<<<'SQL'
            SELECT setval(
                'client_email_group_mapping_id_seq',
                COALESCE((SELECT MAX(id) FROM client_email_group_mapping), 1),
                EXISTS (SELECT 1 FROM client_email_group_mapping)
            )
            SQL);

        if (!$this->hasUniqueEmailIndex()) {
            $this->addSql('CREATE UNIQUE INDEX uniq_client_email_group_mapping_email ON client_email_group_mapping (email)');
        }

        $this->addSql("COMMENT ON COLUMN client_email_group_mapping.created_at IS '(DC2Type:datetime_immutable)'");
        $this->addSql("COMMENT ON COLUMN client_email_group_mapping.updated_at IS '(DC2Type:datetime_immutable)'");
    }

    private function hasUniqueEmailIndex(): bool
    {
        return (bool) $this->connection->fetchOne(<<<'SQL'
            SELECT EXISTS (
                SELECT 1
                FROM pg_index index_definition
                INNER JOIN pg_class table_definition
                    ON table_definition.oid = index_definition.indrelid
                INNER JOIN pg_namespace table_namespace
                    ON table_namespace.oid = table_definition.relnamespace
                INNER JOIN pg_attribute email_column
                    ON email_column.attrelid = table_definition.oid
                   AND email_column.attname = 'email'
                WHERE table_namespace.nspname = 'public'
                  AND table_definition.relname = 'client_email_group_mapping'
                  AND index_definition.indisunique
                  AND index_definition.indnkeyatts = 1
                  AND index_definition.indkey::text = email_column.attnum::text
            )
            SQL);
    }
}
