<?php

namespace App\Services\Api\Actions;

use App\Models\Products\Product;
use App\Models\Setups\Setup;
use App\Services\Api\Exceptions\SetupException;
use Illuminate\Http\Request;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Yaml\Exception\ParseException;

class SetupAction implements ActionInterface
{
    /**
     * Ejecuta la acción setup para obtener configuración YAML del producto
     *
     * @param Request $request
     * @param array $payload
     * @return array
     * @throws SetupException
     */
    public function execute(Request $request, array $payload): array
    {
        /** @var Product $validatedProduct */
        $validatedProduct = $request->input('_validated_product');

        if (!$validatedProduct) {
            throw new SetupException(
                'Product not validated',
                3000,
                401
            );
        }

        $version = $payload['version'] ?? '';

        // Validar que version tiene formato correcto (10 dígitos)
        if (!preg_match('/^\d{10}$/', $version)) {
            throw new SetupException(
                'Invalid version format. Expected YYYYMMDDXX format (10 digits)',
                3003,
                500
            );
        }

        // Buscar setup compatible en la base de datos usando el producto validado
        $setup = Setup::findCompatibleVersion($validatedProduct, $version);

        if (!$setup) {
            throw new SetupException(
                'No compatible setup configuration found for this product version',
                3002,
                404
            );
        }

        // Parsear YAML del campo yaml de la BD
        try {
            $parsedData = Yaml::parse($setup->yaml);

            if (!is_array($parsedData)) {
                throw new SetupException(
                    'Invalid or unreadable setup configuration file',
                    3003,
                    500
                );
            }

            // Devolver el contenido parseado directamente
            return $parsedData;

        } catch (ParseException $e) {
            throw new SetupException(
                'Invalid or unreadable setup configuration file',
                3003,
                500
            );
        } catch (\Exception $e) {
            throw new SetupException(
                'Invalid or unreadable setup configuration file',
                3003,
                500
            );
        }
    }
}
