<?php

namespace App\Services\Api\Actions;

use App\Support\VersionDeContenido;
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'] ?? '';

        // El formato de la versión lo comprueba `VersionDeContenido`: el patrón y el
        // mensaje estaban repetidos en las siete acciones y solo cambiaba el código de
        // error, que sí es de cada familia. Ver MGR-024.
        if (! VersionDeContenido::esValida($version)) {
            throw new SetupException(
                VersionDeContenido::MENSAJE_DE_FORMATO,
                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
            );
        }
    }
}
