<?php

declare(strict_types=1);

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Fixer\Phpdoc;

use PhpCsFixer\AbstractPhpdocTypesFixer;
use PhpCsFixer\DocBlock\TypeExpression;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;

/**
 * @phpstan-type _AutogeneratedInputConfiguration array{
 *  exclude?: list<'$this'|'array'|'bool'|'boolean'|'callable'|'double'|'false'|'float'|'int'|'integer'|'iterable'|'mixed'|'null'|'object'|'parent'|'resource'|'scalar'|'self'|'static'|'string'|'true'|'void'>,
 *  groups?: list<'alias'|'meta'|'simple'>,
 * }
 * @phpstan-type _AutogeneratedComputedConfiguration array{
 *  exclude: list<'$this'|'array'|'bool'|'boolean'|'callable'|'double'|'false'|'float'|'int'|'integer'|'iterable'|'mixed'|'null'|'object'|'parent'|'resource'|'scalar'|'self'|'static'|'string'|'true'|'void'>,
 *  groups: list<'alias'|'meta'|'simple'>,
 * }
 *
 * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
 *
 * @author Graham Campbell <hello@gjcampbell.co.uk>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise.
 */
final class PhpdocTypesFixer extends AbstractPhpdocTypesFixer implements ConfigurableFixerInterface
{
    /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
    use ConfigurableFixerTrait;

    /**
     * Available types, grouped.
     *
     * @var non-empty-array<string, non-empty-list<string>>
     */
    private const POSSIBLE_TYPES = [
        'alias' => [
            'boolean',
            'double',
            'integer',
        ],
        'meta' => [
            '$this',
            'false',
            'mixed',
            'parent',
            'resource',
            'scalar',
            'self',
            'static',
            'true',
            'void',
        ],
        'simple' => [
            'array',
            'bool',
            'callable',
            'float',
            'int',
            'iterable',
            'null',
            'object',
            'string',
        ],
    ];

    /** @var array<string, true> */
    private array $typesSetToFix;

    public function getDefinition(): FixerDefinitionInterface
    {
        return new FixerDefinition(
            'The correct case must be used for standard PHP types in PHPDoc.',
            [
                new CodeSample(
                    <<<'PHP'
                        <?php
                        /**
                         * @param STRING|String[] $bar
                         *
                         * @return inT[]
                         */

                        PHP,
                ),
                new CodeSample(
                    <<<'PHP'
                        <?php
                        /**
                         * @param BOOL $foo
                         *
                         * @return MIXED
                         */

                        PHP,
                    ['groups' => ['simple', 'alias']],
                ),
                new CodeSample(
                    <<<'PHP'
                        <?php
                        /**
                         * @param Resource $foo
                         *
                         * @return VOID
                         */

                        PHP,
                    ['exclude' => ['resource']],
                ),
            ],
        );
    }

    /**
     * {@inheritdoc}
     *
     * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocArrayTypeFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoDuplicateTypesFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesNoDuplicatesFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer.
     * Must run after PhpdocIndentFixer.
     */
    public function getPriority(): int
    {
        /*
         * Should be run before all other docblock fixers apart from the
         * phpdoc_to_comment and phpdoc_indent fixer to make sure all fixers
         * apply correct indentation to new code they add. This should run
         * before alignment of params is done since this fixer might change
         * the type and thereby un-aligning the params. We also must run before
         * the phpdoc_scalar_fixer so that it can make changes after us.
         */
        return 16;
    }

    protected function configurePostNormalisation(): void
    {
        $typesToFix = array_merge(...array_map(static fn (string $group): array => self::POSSIBLE_TYPES[$group], $this->configuration['groups']));
        $this->typesSetToFix = array_combine($typesToFix, array_fill(0, \count($typesToFix), true));

        foreach ($this->configuration['exclude'] as $type) {
            unset($this->typesSetToFix[$type]);
        }
    }

    protected function normalize(string $type): string
    {
        $typeExpression = new TypeExpression($type, null, []);

        $newTypeExpression = $typeExpression->mapTypes(function (TypeExpression $type) {
            if ($type->isUnionType()) {
                return $type;
            }

            $value = $type->toString();
            $valueLower = strtolower($value);
            if (isset($this->typesSetToFix[$valueLower])) {
                return new TypeExpression($valueLower, null, []);
            }

            return $type;
        });

        return $newTypeExpression->toString();
    }

    protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
    {
        $possibleGroups = array_keys(self::POSSIBLE_TYPES);
        $allPossibleTypes = array_merge(...array_values(self::POSSIBLE_TYPES));

        return new FixerConfigurationResolver([
            (new FixerOptionBuilder('exclude', 'List of types to exclude from fixing, regardless of groups.'))
                ->setAllowedTypes(['string[]'])
                ->setAllowedValues([new AllowedValueSubset($allPossibleTypes)])
                ->setDefault([])
                ->getOption(),
            (new FixerOptionBuilder('groups', 'Type groups to fix.'))
                ->setAllowedTypes(['string[]'])
                ->setAllowedValues([new AllowedValueSubset($possibleGroups)])
                ->setDefault($possibleGroups)
                ->getOption(),
        ]);
    }
}
