<?php

declare(strict_types=1);

/**
 * APO-224 follow-up — Delete an unused operator-owned Custom Site Template.
 *
 * URI:   DELETE /api/v1/design/site-templates/custom/{templateId}
 * Scope: design.write
 */
final class MyronDeleteCustomSiteTemplateAction implements MyronAction
{
    public function __construct(
        private readonly MyronTemplateDuplicationActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/site-templates/custom/{templateId}',
            method:        'DELETE',
            domain:        'design',
            resource:      'site-template',
            verb:          'delete-custom',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'templateId' => ['type' => 'string'],
                ],
                'required'   => ['templateId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'id' => ['type' => 'string'],
                    'source_template_id' => ['type' => 'string'],
                    'deleted' => ['type' => 'boolean'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Delete an unused Custom Site Template. Templates used by pages are blocked.',
            sideEffects:     ['deletes page_template_versions rows', 'deletes page_templates row', 'deletes related template chrome assignment rows'],
            preconditions:   ['templateId resolves to a Custom Site Template', 'no pages use the template'],
            postconditions:  ['Custom Site Template is removed from design surfaces and page-template selectors'],
            audienceClass:   4,
            adminAliases:    ['delete-custom-site-template'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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