<?php

namespace App\Services\Api\Actions;

use App\Models\Products\Product;
use App\Models\ScssCdn\ScssCdnBundle;
use App\Services\Api\Exceptions\ScssException;
use App\Services\ScssCdn\ScssCdnImportParser;
use App\Services\ScssCdn\ScssCdnStorageService;
use Illuminate\Http\Request;

class ScssCdnAction implements ActionInterface
{
    /**
     * Ejecuta la acción scss-cdn para obtener archivos SCSS CDN del producto
     *
     * @param Request $request
     * @param array $payload
     * @return array
     * @throws ScssException
     */
    public function execute(Request $request, array $payload): array
    {
        /** @var Product $validatedProduct */
        $validatedProduct = $request->input('_validated_product');

        if (!$validatedProduct) {
            throw new ScssException(
                '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 ScssException(
                'Invalid version format. Expected YYYYMMDDXX format (10 digits)',
                3003,
                500
            );
        }

        // Buscar bundle compatible
        $bundle = ScssCdnBundle::findCompatibleVersion($validatedProduct, $version);

        if (!$bundle) {
            throw new ScssException(
                'No compatible SCSS CDN bundle found for this product version',
                3002,
                404
            );
        }

        // Obtener todos los archivos marcados como servibles
        $servableFiles = $bundle->files()->servable()->get();

        if ($servableFiles->isEmpty()) {
            throw new ScssException(
                'No servable SCSS files found for this bundle',
                3002,
                404
            );
        }

        // Procesar cada archivo servible
        $filesResponse = [];

        foreach ($servableFiles as $file) {
            // Leer contenido desde storage
            $content = ScssCdnStorageService::getFile(
                $validatedProduct,
                $bundle,
                $file->relative_path
            );

            if ($content !== null) {
                // Procesar imports dinámicamente con URLs de 1 hora
                $processedContent = ScssCdnImportParser::processImportsForApi(
                    $content,
                    $bundle,
                    $file->relative_path
                );

                $filesResponse[] = [
                    'filename' => $file->filename,
                    'found' => true,
                    'content' => $processedContent,
                ];
            } else {
                $filesResponse[] = [
                    'filename' => $file->filename,
                    'found' => false,
                    'content' => null,
                ];
            }
        }

        return [
            'files' => $filesResponse,
        ];
    }
}

