<?php

declare(strict_types=1);

/**
 * APO-196 Card 1 — Save site settings.
 *
 * URI:   PATCH /api/v1/administration/site-settings
 * Scope: administration.write
 *
 * Accepts a settings payload plus an optional `favicon` JSON-content
 * envelope. The envelope is decoded to a $_FILES-shaped temp file and
 * passed into the repository alongside the settings array.
 */
final class MyronSaveSiteSettingsAction implements MyronAction
{
    public function __construct(
        private readonly MyronSiteSettingsActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/administration/site-settings',
            method:        'PATCH',
            domain:        'administration',
            resource:      'site-settings',
            verb:          'save',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'settings' => ['type' => 'object'],
                    'favicon'  => ['type' => 'object'],
                ],
                'required'   => ['settings'],
            ],
            outputSchema:  ['type' => 'object', 'properties' => ['updated' => ['type' => 'boolean']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary:       'Save site settings (site name, contact info, locale, defaults, meta). Optional favicon upload via JSON-content envelope.',
            sideEffects:   ['updates site_settings rows', 'refreshes settings cache'],
            preconditions: [],
            postconditions: ['settings persisted; cache refreshed'],
            audienceClass: 4,
            adminAliases:  ['save-site-settings'],
            snapshotInclude: false,
            exposeToMcp:   true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $settings = is_array($input['settings'] ?? null) ? (array) $input['settings'] : [];
            $faviconFile = null;
            $decoded = null;
            $envelope = is_array($input['favicon'] ?? null) ? (array) $input['favicon'] : null;
            if (is_array($envelope) && isset($envelope['contentBase64'])) {
                $tempDir = dirname(__DIR__, 3) . '/tmp/uploads';
                $decoder = new MyronJsonContentEnvelope($tempDir, ['image/x-icon', 'image/vnd.microsoft.icon', 'image/png', 'image/svg+xml']);
                $decoded = $decoder->decode($envelope);
                $faviconFile = $decoded->asUploadedFileArray();
            }
            try {
                return MyronActionResult::ok($this->service->saveSettings($settings, $faviconFile, $caller));
            } finally {
                $decoded?->cleanup();
            }
        } catch (MyronJsonContentEnvelopeError $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
