<?php
/**
 * Door 3 registration for setDesignConvention.
 *
 * @package LolaCoreForBricks
 */

declare(strict_types=1);

namespace LolaCoreForBricks;

use LolaCoreForBricks\Handlers\ConventionHandler;
use LolaCoreForBricks\Support\AbilityI18n;

/**
 * Registers the design convention write ability on the WordPress Abilities API.
 */
final class ConventionWpRegistrar
{
    public function registerAbilities(WPAbilitiesRegistrar $registrar): void
    {
        if (!function_exists('wp_register_ability')) {
            return;
        }

        foreach (ConventionAbilityMap::entries() as $actionId => $entry) {
            $registrar->registerMappedWriteAbility(
                $entry['slug'],
                AbilityI18n::label($actionId),
                AbilityI18n::description($actionId),
                $this->inputSchema($actionId),
                $this->outputSchema($actionId),
                [$this, $this->callbackMethod($actionId)],
                $entry['destructive'],
                $entry['idempotent']
            );
        }
    }

    /**
     * @param array<string, mixed> $input
     * @return array<string, mixed>
     */
    public function executeSetDesignConvention(array $input): array
    {
        $dryRun = (bool) ($input['dry_run'] ?? false);

        return (new ConventionHandler())->setDesignConvention($input, $dryRun);
    }

    private function callbackMethod(string $actionId): string
    {
        return match ($actionId) {
            'set_design_convention' => 'executeSetDesignConvention',
            default                 => 'executeSetDesignConvention',
        };
    }

    /**
     * @return array<string, array<string, string>>
     */
    private function inputSchema(string $actionId): array
    {
        unset($actionId);

        return [
            'dry_run'            => ['type' => 'boolean'],
            'naming_pattern'     => ['type' => 'string'],
            'variable_policy'    => ['type' => 'string'],
            'external_framework' => ['type' => 'string'],
            'protected_prefixes' => ['type' => 'array', 'items' => ['type' => 'string']],
            'notes'              => ['type' => 'string'],
            'examples_valid'     => ['type' => 'array', 'items' => ['type' => 'string']],
            'examples_invalid'   => ['type' => 'array', 'items' => ['type' => 'string']],
        ];
    }

    /**
     * @return array<string, array<string, string>>
     */
    private function outputSchema(string $actionId): array
    {
        unset($actionId);

        return [
            'success'            => ['type' => 'boolean'],
            'message'            => ['type' => 'string'],
            'convention'         => ['type' => 'object'],
            'compliance'         => ['type' => 'object'],
            'detected_framework' => ['type' => 'object'],
            'coverage'           => ['type' => 'object'],
        ];
    }
}
