<?php

declare(strict_types=1);

/**
 * APO-194 Card 4 — Update file metadata (alt_text, description, caption, title).
 *
 * URI:   PATCH /api/v1/files/{fileId}
 * Scope: content.write
 */
final class MyronUpdateFileAction implements MyronAction
{
    public function __construct(
        private readonly MyronFilesActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/files/{fileId}',
            method:        'PATCH',
            domain:        'content',
            resource:      'file',
            verb:          'update',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'fileId'      => ['type' => 'string'],
                    'title'       => ['type' => 'string'],
                    'alt_text'    => ['type' => 'string'],
                    'description' => ['type' => 'string'],
                    'caption'     => ['type' => 'string'],
                ],
                'required'   => ['fileId'],
            ],
            outputSchema:  ['type' => 'object', 'properties' => ['fileId' => ['type' => 'string']]],
            requiredScope:   MyronApiScopes::CONTENT_WRITE,
            summary:         'Update file metadata (title, alt text, description, caption).',
            sideEffects:     ['updates files row metadata columns'],
            preconditions:   ['file exists'],
            postconditions:  ['file metadata reflects input'],
            audienceClass:   4,
            adminAliases:    ['update-file'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->updateMetadata(
                (string) ($input['fileId'] ?? ''),
                $input,
                $caller
            ));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
