<?php

declare(strict_types=1);

final class MyronAppendSiteCustomCssUploadChunkAction implements MyronAction
{
    public function __construct(private readonly MyronUploadSessionService $sessions)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/design/custom-css/site/upload-sessions/{sessionId}/chunks',
            method: 'PATCH',
            domain: 'design',
            resource: 'custom-css-upload-session-chunk',
            verb: 'append',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sessionId' => ['type' => 'string'],
                    'offset' => ['type' => 'integer'],
                    'contentBase64' => ['type' => 'string'],
                    'sha256' => ['type' => 'string'],
                ],
                'required' => ['sessionId', 'offset', 'contentBase64'],
            ],
            outputSchema: ['type' => 'object'],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary: 'Append one base64 chunk to a site custom CSS upload session.',
            sideEffects: ['appends temporary CSS bytes'],
            preconditions: ['session exists', 'offset matches receivedBytes'],
            postconditions: ['session receivedBytes advances by chunk length'],
            audienceClass: 4,
            adminAliases: [],
            snapshotInclude: false,
            exposeToMcp: true,
            mcpAltitude: 'last-resort',
            mcpPreferInstead: ['templates', 'registered sections', 'section variants', 'design tokens'],
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->sessions->append(
                (string) ($input['sessionId'] ?? ''),
                'design.siteCustomCss',
                (int) ($input['offset'] ?? 0),
                (string) ($input['contentBase64'] ?? ''),
                (string) ($input['sha256'] ?? '')
            ));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
