<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\SellerDomain;
use Symfony\Component\HttpFoundation\Response;

class DetectCustomDomain
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $host = $request->getHost();

        // Get main domain from APP_URL (strip protocol and trailing slash)
        $mainDomain = parse_url(config('app.url'), PHP_URL_HOST) ?? 'localhost';

        // Check if this is NOT our main domain (could be a custom domain)
        if ($host !== $mainDomain && $host !== 'localhost' && $host !== '127.0.0.1') {
            // Look for verified custom domain
            $sellerDomain = SellerDomain::where('domain', $host)
                ->where('is_active', true)
                ->whereNotNull('verified_at')
                ->first();

            if ($sellerDomain) {
                // Store the SellerDomain in the request for later use
                $request->attributes->set('sellerDomain', $sellerDomain);
                $request->attributes->set('isCustomDomain', true);
            }
        }

        return $next($request);
    }
}
