<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/files/upload-sessions/{sessionId}/chunks',
            method: 'PATCH',
            domain: 'content',
            resource: 'file-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::CONTENT_WRITE,
            summary: 'Append one base64 chunk to a file upload session at the expected byte offset.',
            sideEffects: ['appends temporary upload bytes'],
            preconditions: ['session exists', 'offset matches receivedBytes'],
            postconditions: ['session receivedBytes advances by chunk length'],
            audienceClass: 4,
            adminAliases: [],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->sessions->append(
                (string) ($input['sessionId'] ?? ''),
                'file',
                (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());
        }
    }
}
