<?php

declare(strict_types=1);

final class MyronGetTrafficSourcesAction implements MyronAction
{
    public function __construct(private readonly MyronSiteAnalyticsRepository $repo)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/analytics/traffic-sources',
            method: 'GET',
            domain: 'analytics',
            resource: 'traffic-sources',
            verb: 'get',
            inputSchema: ['type' => 'object', 'properties' => ['days' => [], 'limit' => []]],
            outputSchema: ['type' => 'object'],
            requiredScope: MyronApiScopes::ADMINISTRATION_READ,
            summary: 'List top referrer domains by distinct anonymous visit count for the selected day range.',
            sideEffects: [],
            preconditions: ['caller holds administration.read'],
            postconditions: ['ranked referrer domains returned'],
            audienceClass: 2,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        if (!myronAnalyticsEnabled()) {
            return MyronActionResult::ok(['sources' => []]);
        }
        return MyronActionResult::ok([
            'sources' => $this->repo->getTrafficSources((int) ($input['days'] ?? 30), (int) ($input['limit'] ?? 10)),
        ]);
    }
}
