<?php

/**
 * This file contains \QUI\Cache\MCP\Provider
 */

namespace QUI\Cache\MCP;

use Mcp\Schema\Result\CallToolResult;
use Mcp\Server\Builder;
use QUI\AI\MCP\ProviderInterface;
use QUI\AI\MCP\Server;
use QUI\AI\MCP\ToolHelper;
use QUI\Cache\Handler;
use QUI\Permissions\Permission;
use Throwable;

/**
 * Cache module MCP provider
 */
class Provider implements ProviderInterface
{
    private const PERMISSION = 'quiqqer.cache.mcp';

    public function register(Builder $serverBuilder): void
    {
        if (!$this->canUseMcp()) {
            return;
        }

        $serverBuilder->addTool(
            function (): array | CallToolResult {
                try {
                    $this->checkPermission();

                    $Handler = Handler::init();
                    $cacheDir = $Handler->getCacheDir();

                    $Handler->clearCache();

                    return [
                        'success' => true,
                        'cleared' => [
                            'website'
                        ],
                        'cacheDir' => $cacheDir
                    ];
                } catch (Throwable $Exception) {
                    return ToolHelper::parseExceptionToResult($Exception);
                }
            },
            name: 'quiqqer_website_cache_clear',
            description: 'Clears the generated website cache from the quiqqer/cache module.',
            inputSchema: [
                'type' => 'object',
                'additionalProperties' => false,
                'properties' => (object)[]
            ]
        );
    }

    private function canUseMcp(): bool
    {
        try {
            $this->checkPermission();

            return true;
        } catch (Throwable) {
            return false;
        }
    }

    private function checkPermission(): void
    {
        Permission::checkPermission(
            self::PERMISSION,
            Server::getRequestUser()
        );
    }
}
