<?php

declare(strict_types=1);

final class MyronBundleRecentEventsAction implements MyronAction
{
    public function __construct(private readonly PDO $pdo, private readonly MyronSiteTypeRegistryRepository $siteTypes) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/bundles/{bundleId}/events',
            method: 'GET',
            domain: 'administration',
            resource: 'bundle-event',
            verb: 'recentEvents',
            inputSchema: ['type' => 'object', 'properties' => ['bundleId' => ['type' => 'string'], 'limit' => ['type' => 'string']], 'required' => ['bundleId']],
            outputSchema: ['type' => 'object', 'properties' => ['events' => ['type' => 'array']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_READ,
            summary: 'List recent disable/enable audit events for a site type bundle.',
            audienceClass: 3,
            adminAliases: ['bundles.recentEvents'],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $bundleId = trim((string) ($input['bundleId'] ?? ''));
        if ($bundleId === '' || !is_array($this->siteTypes->findSiteTypeById($bundleId))) {
            return MyronActionResult::error('not_found', 'Bundle not found.');
        }
        $limit = max(1, min(50, (int) ($input['limit'] ?? 10)));
        $statement = $this->pdo->query(
            'SELECT *
             FROM bundle_activation_audit
             WHERE context IN (\'disable\', \'enable\')
             ORDER BY created_at DESC, id DESC
             LIMIT ' . ($limit * 5)
        );
        $events = [];
        foreach (($statement ? $statement->fetchAll(PDO::FETCH_ASSOC) : []) as $row) {
            if (!is_array($row)) {
                continue;
            }
            $after = json_decode((string) ($row['after_json'] ?? '{}'), true);
            if (!is_array($after) || (string) ($after['bundle_id'] ?? '') !== $bundleId) {
                continue;
            }
            $events[] = [
                'id' => (string) ($row['id'] ?? ''),
                'context' => (string) ($row['context'] ?? ''),
                'actor_id' => (string) ($row['actor_id'] ?? ''),
                'primary_bundle_id' => (string) ($row['primary_bundle_id'] ?? ''),
                'before' => json_decode((string) ($row['before_json'] ?? '{}'), true) ?: [],
                'after' => $after,
                'created_at' => (string) ($row['created_at'] ?? ''),
            ];
            if (count($events) >= $limit) {
                break;
            }
        }

        return MyronActionResult::ok(['events' => $events]);
    }
}
