<?php

declare(strict_types=1);

/**
 * APO-193 Card 4 — Update the configuration of a footer variant.
 *
 * URI:   PATCH /api/v1/design/footers/{variantId}/configuration
 * Scope: design.write
 */
final class MyronUpdateFooterConfigurationAction implements MyronAction
{
    public function __construct(
        private readonly MyronFooterDesignActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/footers/{variantId}/configuration',
            method:        'PATCH',
            domain:        'design',
            resource:      'footer',
            verb:          'update-configuration',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'variantId'    => ['type' => 'string'],
                    'visibility'   => ['type' => 'object'],
                    'contentByZone' => ['type' => 'object'],
                ],
                'required'   => ['variantId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'variantId'    => ['type' => 'string'],
                    'zonesUpdated' => ['type' => 'integer'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Update a footer variant\'s configuration: zone visibility map and per-zone content payload.',
            sideEffects:     ['writes footer_designs.zone_visibility', 'writes footer_designs.zone_content'],
            preconditions:   ['variant exists in valid variants'],
            postconditions:  ['variant configuration matches input'],
            audienceClass:   4,
            adminAliases:    ['update-footer-configuration'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $visibility    = is_array($input['visibility'] ?? null) ? (array) $input['visibility'] : [];
            $contentByZone = is_array($input['contentByZone'] ?? null) ? (array) $input['contentByZone'] : [];
            // Normalise visibility values to booleans.
            foreach ($visibility as $k => $v) {
                $visibility[$k] = (bool) $v;
            }
            return MyronActionResult::ok($this->service->updateConfiguration(
                (string) ($input['variantId'] ?? ''),
                $visibility,
                $contentByZone,
                $caller
            ));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
