<?php

declare(strict_types=1);

final class MyronCommitFileUploadSessionAction implements MyronAction
{
    public function __construct(
        private readonly MyronUploadSessionService $sessions,
        private readonly MyronFilesActionService $files,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/files/upload-sessions/{sessionId}/commit',
            method: 'POST',
            domain: 'content',
            resource: 'file-upload-session',
            verb: 'commit',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sessionId' => ['type' => 'string'],
                ],
                'required' => ['sessionId'],
            ],
            outputSchema: ['type' => 'object'],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Commit a completed file upload session into the file library.',
            sideEffects: ['inserts files row', 'writes bytes to public/uploads/', 'deletes temporary session'],
            preconditions: ['session is complete', 'session sha256 matches payload'],
            postconditions: ['file row exists; upload session removed'],
            audienceClass: 4,
            adminAliases: [],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $sessionId = (string) ($input['sessionId'] ?? '');
        try {
            $complete = $this->sessions->complete($sessionId, 'file');
            $result = $this->files->uploadFromMultipart($complete['uploadedFile'], $complete['metadata'], $caller);
            $this->sessions->cleanup($sessionId);
            return MyronActionResult::ok($result);
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
