<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class SanctumOrTrustedOrigin
{
    public function handle(Request $request, Closure $next): Response
    {
        // Authenticated via Sanctum (cookie or token) — let it through, auth()->user() is set.
        if ($user = $request->user('sanctum')) {
            Auth::setUser($user);
            return $next($request);
        }

        // Unauthenticated, but coming from our own frontend — let it through too.
        $origin = $request->headers->get('Origin') ?? $request->headers->get('Referer');
        $trusted = config('app.trusted_frontend_origins', []);

        foreach ($trusted as $trustedOrigin) {
            if ($origin && str_starts_with($origin, $trustedOrigin)) {
                return $next($request);
            }
        }

        abort(403, 'Forbidden.');
    }
}
