<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/design/custom-css/site/upload-session',
            method: 'POST',
            domain: 'design',
            resource: 'custom-css-upload-session',
            verb: 'create',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sizeBytes' => ['type' => 'integer'],
                    'sha256' => ['type' => 'string'],
                ],
                'required' => ['sizeBytes', 'sha256'],
            ],
            outputSchema: ['type' => 'object'],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary: 'Create a chunked upload session for site custom CSS.',
            sideEffects: ['creates temporary upload session metadata'],
            preconditions: ['caller holds design.write'],
            postconditions: ['upload session accepts ordered CSS chunks'],
            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->begin(
                'design.siteCustomCss',
                'site-custom.css',
                'text/css',
                (int) ($input['sizeBytes'] ?? 0),
                (string) ($input['sha256'] ?? '')
            ));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
