<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\DealFlowBundle\Entity\Deal;
use MauticPlugin\DealFlowBundle\Entity\DealField;

final class Version_0_5_0 extends AbstractMigration
{
    protected function isApplicable(Schema $schema): bool
    {
        $dealTable  = $this->concatPrefix(Deal::TABLE_NAME);
        $fieldTable = $this->concatPrefix(DealField::TABLE_NAME);

        return $schema->hasTable($dealTable)
            && (
                !$schema->hasTable($fieldTable)
                || !$schema->getTable($dealTable)->hasColumn('custom_fields_json')
            );
    }

    protected function up(): void
    {
        $connection    = $this->entityManager->getConnection();
        $schemaManager = $connection->createSchemaManager();
        $dealTable     = $this->concatPrefix(Deal::TABLE_NAME);
        $fieldTable    = $this->concatPrefix(DealField::TABLE_NAME);

        if (!$schemaManager->tablesExist([$fieldTable])) {
            $connection->executeStatement(sprintf(
                'CREATE TABLE `%s` (
                    `id` INT AUTO_INCREMENT NOT NULL,
                    `label` VARCHAR(191) NOT NULL,
                    `alias` VARCHAR(191) NOT NULL,
                    `field_type` VARCHAR(32) NOT NULL,
                    `options_json` LONGTEXT NOT NULL,
                    `is_required` TINYINT(1) NOT NULL DEFAULT 0,
                    `show_in_list` TINYINT(1) NOT NULL DEFAULT 0,
                    `sort_order` INT NOT NULL DEFAULT 0,
                    `is_active` TINYINT(1) NOT NULL DEFAULT 1,
                    `created_at` DATETIME NOT NULL,
                    `updated_at` DATETIME NOT NULL,
                    UNIQUE INDEX `dealflow_field_alias_unique` (`alias`),
                    INDEX `dealflow_field_sort_idx` (`sort_order`),
                    INDEX `dealflow_field_active_idx` (`is_active`),
                    PRIMARY KEY(`id`)
                ) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB',
                $fieldTable
            ));
        }

        $dealTableDetails = $schemaManager->introspectTable($dealTable);
        if (!$dealTableDetails->hasColumn('custom_fields_json')) {
            $connection->executeStatement(sprintf(
                'ALTER TABLE `%s` ADD `custom_fields_json` LONGTEXT DEFAULT NULL',
                $dealTable
            ));
        }
    }
}
