<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;

class AddCsrfTokenToCsrfCookieResponse
{
    /**
     * When the client requests GET /sanctum/csrf-cookie with Accept: application/json,
     * return the CSRF token in the response body so the SPA can use it when it cannot
     * read the cookie (e.g. frontend and API on different origins: localhost:5173 vs 8000, or azaanhospital.com vs backend.azaanhospital.com).
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): SymfonyResponse
    {
        $response = $next($request);

        if (
            $request->is('sanctum/csrf-cookie')
            && $request->expectsJson()
            && $request->hasSession()
        ) {
            $newResponse = new Response(
                ['csrf_token' => $request->session()->token()],
                200,
                ['Content-Type' => 'application/json']
            );
            foreach ($response->headers->getCookies() as $cookie) {
                $newResponse->headers->setCookie($cookie);
            }

            return $newResponse;
        }

        return $response;
    }
}
