<?php

declare(strict_types=1);

final class MyronUploadVideoCaptionsAction implements MyronAction
{
    public function __construct(private readonly MyronMediaAccessibilityActionService $service)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/files/video-assets/{assetId}/captions',
            method: 'PUT',
            domain: 'content',
            resource: 'video-captions',
            verb: 'upload',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'assetId' => ['type' => 'string'],
                    'filename' => ['type' => 'string'],
                    'contentType' => ['type' => 'string'],
                    'contentBase64' => ['type' => 'string'],
                    'sizeBytes' => ['type' => 'integer'],
                    'sha256' => ['type' => 'string'],
                    'metadata' => ['type' => 'object'],
                ],
                'required' => ['assetId', 'filename', 'contentType', 'contentBase64', 'sizeBytes', 'sha256'],
            ],
            outputSchema: ['type' => 'object'],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Upload or replace captions for a video asset.',
            sideEffects: ['uploads caption file', 'writes media_accessibility_attachments'],
            preconditions: ['video asset exists', 'caption file is .vtt, .srt, or .txt'],
            postconditions: ['video asset has a captions attachment'],
            audienceClass: 4,
            adminAliases: ['upload-video-captions'],
            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->service->uploadVideoCaptionsFromEnvelope((string) ($input['assetId'] ?? ''), $input, $metadata, $caller));
        } catch (MyronJsonContentEnvelopeError|InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
