<?php

namespace App\Http\Middleware\Solicitor;

use App\Models\Solicitor\Solicitor;
use Closure;
use Illuminate\Http\Request;
use App\Models\User\User;

class SetSolicitorFromDomain {
    public function handle(Request $request, Closure $next) {
        // Default: no tenant bound
        app()->instance(Solicitor::class, null);

        // Auth and workspace routes never need a tenant resolved
        if ($request->is('login', 'logout', 'workspace', 'workspace/*')) {
            return $next($request);
        }

        $host      = $request->getHost();
        $subdomain = explode('.', $host)[0];
        $isPlatformSubdomain = in_array($subdomain, ['ha', 'hastaging'], true);
        $isLocalhost = app()->isLocal() && in_array($host, ['localhost', '127.0.0.1'], true);

        // Resolve tenant from domain for proper solicitor subdomains
        if (!$isPlatformSubdomain && !$isLocalhost) {
            $tenant = Solicitor::where('domain', $subdomain)->first();

            if (!$tenant) {
                abort(403, 'Solicitor portal not found for this domain.');
            }

            app()->instance(Solicitor::class, $tenant);
            return $next($request);
        } elseif($isPlatformSubdomain && app()->isProduction() && $request->session()->has('impersonator_id') && $request->session()->has('impersonated_id')) {
            app()->instance(Solicitor::class, User::find(session()->get('impersonated_id')->solicitor));
        }

        // Platform subdomain or localhost — resolve from session workspace selection
        $workspaceId = session('workspace_solicitor_id');
        if ($workspaceId) {
            $tenant = Solicitor::find($workspaceId);
            if ($tenant) {
                app()->instance(Solicitor::class, $tenant);
            }
        }

        return $next($request);
    }
}
