<?php

namespace App\Http\Controllers\ScssCdn;

use App\Http\Controllers\Controller;
use App\Models\ScssCdn\ScssCdnFile;
use App\Services\ScssCdn\ScssCdnStorageService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class CdnFileController extends Controller
{
    /**
     * Sirve un archivo SCSS vía URL firmada
     *
     * @param Request $request
     * @param string $token Token seguro del archivo
     * @param string $filename Nombre del archivo
     * @return Response
     */
    public function serve(Request $request, string $token, string $filename): Response
    {
        // Buscar archivo por token
        $file = ScssCdnFile::where('secure_token', $token)
            ->where('filename', $filename)
            ->first();

        if (!$file) {
            abort(404, 'Archivo no encontrado');
        }

        // Cargar relaciones necesarias
        $file->load(['bundle.product']);

        // Leer contenido del storage
        $content = ScssCdnStorageService::getFile(
            $file->bundle->product,
            $file->bundle,
            $file->relative_path
        );

        if ($content === null) {
            abort(404, 'Contenido del archivo no encontrado');
        }

        // Retornar respuesta con headers apropiados
        return response($content, 200)
            ->header('Content-Type', 'text/css; charset=utf-8')
            ->header('Cache-Control', 'public, max-age=31536000, immutable') // 1 año de cache
            ->header('X-Content-Type-Options', 'nosniff');
    }
}
