<?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\DealNote;
use MauticPlugin\DealFlowBundle\Entity\InboundWebhookSource;

final class Version_0_6_4 extends AbstractMigration
{
    protected function isApplicable(Schema $schema): bool
    {
        $tableName = $this->concatPrefix(Deal::TABLE_NAME);

        return $schema->hasTable($tableName)
            && !$schema->getTable($tableName)->hasColumn('qualification');
    }

    protected function up(): void
    {
        $connection    = $this->entityManager->getConnection();
        $schemaManager = $connection->createSchemaManager();

        $dealsTable = $this->concatPrefix(Deal::TABLE_NAME);
        $table      = $schemaManager->introspectTable($dealsTable);

        if (!$table->hasColumn('qualification')) {
            $connection->executeStatement(sprintf(
                "ALTER TABLE `%s` ADD `qualification` VARCHAR(20) NOT NULL DEFAULT 'unqualified' AFTER `status`",
                $dealsTable
            ));
        }

        $notesTable = $this->concatPrefix(DealNote::TABLE_NAME);
        $table      = $schemaManager->introspectTable($notesTable);

        if (!$table->hasColumn('activity_type')) {
            $connection->executeStatement(sprintf(
                "ALTER TABLE `%s` ADD `activity_type` VARCHAR(20) NOT NULL DEFAULT 'note' AFTER `source_ref`",
                $notesTable
            ));
        }

        $webhookTable = $this->concatPrefix(InboundWebhookSource::TABLE_NAME);
        $table        = $schemaManager->introspectTable($webhookTable);

        if (!$table->hasColumn('field_mapping')) {
            $connection->executeStatement(sprintf(
                'ALTER TABLE `%s` ADD `field_mapping` LONGTEXT DEFAULT NULL AFTER `is_active`',
                $webhookTable
            ));
        }
    }
}
