<?php

declare(strict_types=1);

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

namespace TYPO3\CMS\Core\Database\Schema\EventListener;

use Doctrine\DBAL\Event\SchemaColumnDefinitionEventArgs;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\MariaDb1027Platform;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Types\Type;

/**
 * Event listener to handle additional processing for custom
 * doctrine types.
 */
class SchemaColumnDefinitionListener
{
    /**
     * Listener for column definition events. This intercepts definitions
     * for custom doctrine types and builds the appropriate Column Object.
     *
     * @param \Doctrine\DBAL\Event\SchemaColumnDefinitionEventArgs $event
     * @throws \Doctrine\DBAL\Exception
     */
    public function onSchemaColumnDefinition(SchemaColumnDefinitionEventArgs $event)
    {
        $tableColumn = $event->getTableColumn();
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);

        $dbType = $this->getDatabaseType($tableColumn['type']);
        if ($dbType !== 'enum' && $dbType !== 'set') {
            return;
        }

        $column = $this->getEnumerationTableColumnDefinition(
            $tableColumn,
            $event->getConnection()->getDatabasePlatform()
        );

        $event->setColumn($column);
        $event->preventDefault();
    }

    /**
     * Build a Doctrine column object for TYPE/TYPE columns.
     *
     * @param array $tableColumn
     * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
     * @return \Doctrine\DBAL\Schema\Column
     * @throws \Doctrine\DBAL\Exception
     * @todo: The $tableColumn source currently only support MySQL definition style.
     */
    protected function getEnumerationTableColumnDefinition(array $tableColumn, AbstractPlatform $platform): Column
    {
        $default = $tableColumn['default'] ?? null;
        // Doctrine DBAL retrieves for MariaDB `ENUM()` and `SET()` field default values quotes with single quotes,
        // which leads to an endless field change reporting recursion in the database analyzer. The default value
        // is now trimmed to ensure a working field compare within `TYPO3\CMS\Core\Database\Schema\Comparator`.
        if (is_string($default) && $platform instanceof MariaDb1027Platform && str_starts_with($default, "'") && str_ends_with($default, "'")) {
            $default = trim($default, "'");
        }
        $options = [
            'length' => $tableColumn['length'] ?? null,
            'unsigned' => false,
            'fixed' => false,
            'default' => $default,
            'notnull' => ($tableColumn['null'] ?? '') !== 'YES',
            'scale' => null,
            'precision' => null,
            'autoincrement' => false,
            'comment' => $tableColumn['comment'] ?? null,
        ];

        $dbType = $this->getDatabaseType($tableColumn['type']);
        $doctrineType = $platform->getDoctrineTypeMapping($dbType);

        $column = new Column($tableColumn['field'] ?? '', Type::getType($doctrineType), $options);
        $column->setPlatformOption('unquotedValues', $this->getUnquotedEnumerationValues($tableColumn['type']));

        return $column;
    }

    /**
     * Extract the field type from the definition string
     *
     * @param string $typeDefinition
     * @return string
     */
    protected function getDatabaseType(string $typeDefinition): string
    {
        $dbType = strtolower($typeDefinition);
        $dbType = strtok($dbType, '(), ');

        return $dbType;
    }

    /**
     * @param string $typeDefinition
     * @return array
     */
    protected function getUnquotedEnumerationValues(string $typeDefinition): array
    {
        $valuesDefinition = preg_replace('#^(enum|set)\((.*)\)\s*$#i', '$2', $typeDefinition) ?? '';
        $quoteChar = $valuesDefinition[0];
        $separator = $quoteChar . ',' . $quoteChar;

        $valuesDefinition = preg_replace(
            '#' . $quoteChar . ',\s*' . $quoteChar . '#',
            $separator,
            $valuesDefinition
        ) ?? '';

        $values = explode($quoteChar . ',' . $quoteChar, substr($valuesDefinition, 1, -1));

        return array_map(
            static function (string $value) use ($quoteChar) {
                return str_replace($quoteChar . $quoteChar, $quoteChar, $value);
            },
            $values
        );
    }
}
