<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Migrations;

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

final class Version_0_6_1 extends AbstractMigration
{
    protected function isApplicable(Schema $schema): bool
    {
        return $schema->hasTable($this->concatPrefix(Pipeline::TABLE_NAME));
    }

    protected function up(): void
    {
        $connection   = $this->entityManager->getConnection();
        $tableName    = $this->concatPrefix(Pipeline::TABLE_NAME);
        $defaultId    = $connection->fetchOne(sprintf('SELECT id FROM `%s` WHERE is_default = 1 ORDER BY id ASC LIMIT 1', $tableName));
        $targetName   = 'Sales Pipeline';
        $legacyName   = 'Deal Flow';
        $timestamp    = (new \DateTimeImmutable())->format('Y-m-d H:i:s');

        if (false === $defaultId) {
            return;
        }

        $defaultId = (int) $defaultId;
        $currentName = $connection->fetchOne(
            sprintf('SELECT name FROM `%s` WHERE id = :id', $tableName),
            ['id' => $defaultId]
        );

        if (!in_array($currentName, [$legacyName, null, ''], true)) {
            return;
        }

        $connection->update(
            $tableName,
            [
                'name'       => $targetName,
                'updated_at' => $timestamp,
            ],
            ['id' => $defaultId]
        );
    }
}
