<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Stancl\Tenancy\Database\Models\Domain;
use Symfony\Component\HttpFoundation\Response;

/**
 * Reflects the request Origin back as the single allowed CORS origin when it
 * resolves to a registered tenant domain. Must run before HandleCors so the
 * override is in place for both preflight and actual requests. Keying off the
 * Origin header (not x-tenant) is required because browsers omit custom headers
 * on the preflight OPTIONS request.
 */
class SetTenantCorsOrigins
{
    public function handle(Request $request, Closure $next): Response
    {
        $origin = $request->headers->get('Origin');

        if ($origin !== null && $this->isTenantOrigin($origin)) {
            Config::set('cors.allowed_origins', [$origin]);
        }

        return $next($request);
    }

    private function isTenantOrigin(string $origin): bool
    {
        $host = parse_url($origin, PHP_URL_HOST);

        if (!is_string($host) || $host === '') {
            return false;
        }

        $bareHost = preg_replace('/^www\./', '', $host);
        $candidates = array_values(array_unique([$host, $bareHost, 'www.' . $bareHost]));

        return Cache::remember(
            'cors_tenant_origin:' . $host,
            now()->addMinutes(5),
            fn (): bool => Domain::query()->whereIn('domain', $candidates)->exists()
        );
    }
}
