<?php

declare(strict_types=1);

/**
 * Replace an existing file payload while preserving its stable file ID.
 *
 * URI:   PUT /api/v1/files/{fileId}/content
 * Scope: content.write
 */
final class MyronReplaceFileContentAction implements MyronAction
{
    public function __construct(
        private readonly MyronFilesActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/files/{fileId}/content',
            method:        'PUT',
            domain:        'content',
            resource:      'file-content',
            verb:          'replace',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'fileId'        => ['type' => 'string'],
                    'filename'      => ['type' => 'string'],
                    'contentType'   => ['type' => 'string'],
                    'contentBase64' => ['type' => 'string'],
                    'sizeBytes'     => ['type' => 'integer'],
                    'sha256'        => ['type' => 'string'],
                    'metadata'      => ['type' => 'object'],
                ],
                'required'   => ['fileId', 'filename', 'contentType', 'contentBase64', 'sizeBytes', 'sha256'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'id' => ['type' => 'string'],
                    'file_url' => ['type' => 'string'],
                    'revisioned_file_url' => ['type' => 'string'],
                    'file_revision' => ['type' => 'string'],
                    'original_filename' => ['type' => 'string'],
                    'mime_type' => ['type' => 'string'],
                    'file_size_bytes' => ['type' => 'integer'],
                ],
            ],
            requiredScope:   MyronApiScopes::CONTENT_WRITE,
            summary:         'Replace an existing file payload while preserving the same file ID and all existing content references. Metadata PATCH remains metadata-only; this action mutates stored bytes and returns updated revisioned URL data.',
            sideEffects:     ['replaces stored file bytes', 'updates file MIME/size/dimensions columns', 'removes stale sidecars and image renditions', 'preserves files.id'],
            preconditions:   ['file exists', 'replacement content envelope is valid', 'replacement media class matches existing asset'],
            postconditions:  ['same file ID resolves to new bytes', 'generated revisioned URLs change after replacement'],
            audienceClass:   4,
            adminAliases:    ['replace-file'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $envelope = [
            'filename'      => $input['filename']      ?? '',
            'contentType'   => $input['contentType']   ?? '',
            'contentBase64' => $input['contentBase64'] ?? '',
            'sizeBytes'     => $input['sizeBytes']     ?? 0,
            'sha256'        => $input['sha256']        ?? '',
        ];
        $metadata = is_array($input['metadata'] ?? null) ? (array) $input['metadata'] : [];

        try {
            return MyronActionResult::ok($this->service->replaceFromEnvelope(
                (string) ($input['fileId'] ?? ''),
                $envelope,
                $metadata,
                $caller
            ));
        } catch (MyronJsonContentEnvelopeError $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
