<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
use Symfony\Component\HttpFoundation\Response;

class UniversalTenancy
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // 判斷是否為中央域名
        $centralDomains = config('tenancy.central_domains', []);

        // [Hack] Demo 環境特殊規則：
        // 如果設定了 demo_tenant_port (e.g. 8081)，且請求端口相符，強制視為租戶請求
        $demoPort = config('tenancy.demo_tenant_port');
        if ($demoPort && $request->getPort() == $demoPort) {
            return app(InitializeTenancyByDomain::class)->handle($request, $next);
        }

        if (in_array($request->getHost(), $centralDomains)) {
            // 如果是中央域名，不進行租戶初始化，直接繼續往下執行 (使用預設資料庫)
            return $next($request);
        }

        // 如果不是中央域名，嘗試透過域名初始化租戶
        // 若找不到租戶，InitializeTenancyByDomain 會拋出異常
        return app(InitializeTenancyByDomain::class)->handle($request, $next);
    }
}
