<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/files/upload-sessions',
            method: 'POST',
            domain: 'content',
            resource: 'file-upload-session',
            verb: 'create',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'filename' => ['type' => 'string'],
                    'contentType' => ['type' => 'string'],
                    'sizeBytes' => ['type' => 'integer'],
                    'sha256' => ['type' => 'string'],
                    'metadata' => ['type' => 'object'],
                ],
                'required' => ['filename', 'contentType', 'sizeBytes', 'sha256'],
            ],
            outputSchema: ['type' => 'object'],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Create a chunked file upload session for MCP-safe binary transfer.',
            sideEffects: ['creates temporary upload session metadata'],
            preconditions: ['caller holds content.write'],
            postconditions: ['upload session accepts ordered chunks'],
            audienceClass: 4,
            adminAliases: [],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $metadata = is_array($input['metadata'] ?? null) ? (array) $input['metadata'] : [];
            return MyronActionResult::ok($this->sessions->begin(
                'file',
                (string) ($input['filename'] ?? ''),
                (string) ($input['contentType'] ?? ''),
                (int) ($input['sizeBytes'] ?? 0),
                (string) ($input['sha256'] ?? ''),
                $metadata
            ));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
