<?php

declare(strict_types=1);

final class MicTableCreateAction implements MyronAction
{
    public function __construct(private readonly MicTableService $service)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/tables',
            method: 'POST',
            domain: 'content.tables',
            resource: 'table',
            verb: 'create',
            inputSchema: $this->schema(true),
            outputSchema: ['type' => 'object', 'properties' => ['table' => ['type' => 'object']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Create a reusable Content Bank table.',
            sideEffects: ['inserts mic_tables row'],
            audienceClass: 4,
            adminAliases: ['tables.create'],
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->create($input, $caller));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        }
    }

    private function schema(bool $requireName): array
    {
        return [
            'type' => 'object',
            'properties' => [
                'name' => ['type' => 'string'],
                'description' => ['type' => 'string'],
                'caption' => ['type' => 'string'],
                'columns' => ['type' => 'array'],
                'rows' => ['type' => 'array'],
                'header_style' => ['type' => 'string'],
                'responsive_strategy' => ['type' => 'string'],
            ],
            'required' => $requireName ? ['name'] : [],
        ];
    }
}

