<?php

namespace App\Http\Middleware;  // Asegúrate de que el namespace sea correcto

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;  // Importa esto si no lo tienes
use Symfony\Component\HttpFoundation\BinaryFileResponse;  // Opcional, si lo usas en condicionales
use Symfony\Component\HttpFoundation\StreamedResponse;    // Agrega este import para mayor claridad

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // For OPTIONS preflight requests
        if ($request->isMethod('OPTIONS')) {
            $response = response('', 200);
        } else {
            $response = $next($request);
        }

        // Headers a agregar
        $headers = [
            'Access-Control-Allow-Origin'      => '*',  // Cambia por 'http://localhost:4200' en prod
            'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS, PUT, DELETE, PATCH',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => '86400',
            'Access-Control-Allow-Headers'     => 'X-Requested-With, Content-Type, X-Token-Auth, Authorization, Accept, Origin, Cache-Control',
            'Access-Control-Expose-Headers'    => 'Content-Disposition, Content-Type'  // Agregué Content-Type por si acaso
        ];

        // ✅ SIEMPRE usa headers->set() para evitar errores en StreamedResponse/BinaryFileResponse
        foreach ($headers as $key => $value) {
            $response->headers->set($key, $value);
        }

        return $response;
    }
}