<?php

declare(strict_types=1);

/**
 * Upload a file via multipart/form-data under the canonical /api/v1 auth path.
 *
 * The public route accepts POST /api/v1/files with multipart/form-data and
 * internally dispatches here so bearer auth, scope checks, rate limiting, and
 * AI audit logging remain owned by MyronActionDispatcher.
 */
final class MyronUploadMultipartFileAction implements MyronAction
{
    public function __construct(
        private readonly MyronFilesActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/files/multipart',
            method:        'POST',
            domain:        'content',
            resource:      'file-multipart',
            verb:          'upload',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'uploadedFile' => ['type' => 'object'],
                    'metadata' => ['type' => 'object'],
                ],
                'required'   => ['uploadedFile'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'id'             => ['type' => 'string'],
                    'file_url'       => ['type' => 'string'],
                    'original_filename' => ['type' => 'string'],
                    'mime_type'      => ['type' => 'string'],
                    'file_size_bytes' => ['type' => 'integer'],
                ],
            ],
            requiredScope:   MyronApiScopes::CONTENT_WRITE,
            summary:         'Upload a file using multipart/form-data with canonical bearer authorization.',
            sideEffects:     ['inserts files row', 'writes bytes to public/uploads/'],
            preconditions:   ['multipart field "file" is present', 'caller holds content.write'],
            postconditions:  ['file row exists; bytes persisted; metadata recorded'],
            audienceClass:   4,
            adminAliases:    ['upload-file-multipart'],
            snapshotInclude: false,
            exposeToMcp:     false,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $uploadedFile = is_array($input['uploadedFile'] ?? null) ? (array) $input['uploadedFile'] : [];
        $metadata = is_array($input['metadata'] ?? null) ? (array) $input['metadata'] : [];

        try {
            return MyronActionResult::ok($this->service->uploadFromMultipart($uploadedFile, $metadata, $caller));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
