<?php

declare(strict_types=1);

/**
 * APO-194 Card 4 — Delete a file.
 *
 * URI:   DELETE /api/v1/files/{fileId}
 * Scope: content.write
 */
final class MyronDeleteFileAction implements MyronAction
{
    public function __construct(
        private readonly MyronFilesActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/files/{fileId}',
            method:        'DELETE',
            domain:        'content',
            resource:      'file',
            verb:          'delete',
            inputSchema:   [
                'type'       => 'object',
                'properties' => ['fileId' => ['type' => 'string']],
                'required'   => ['fileId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'fileId'  => ['type' => 'string'],
                    'deleted' => ['type' => 'boolean'],
                ],
            ],
            requiredScope:   MyronApiScopes::CONTENT_WRITE,
            summary:         'Delete a file (removes the file row and the bytes from storage).',
            sideEffects:     ['deletes files row; removes file bytes from public/uploads/'],
            preconditions:   ['file exists; file not currently in use by a published page or section variant'],
            postconditions:  ['file row removed; bytes purged'],
            audienceClass:   4,
            adminAliases:    ['delete-file'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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