<?php

namespace App\Http\Middleware;

use App\Models\Tenant;
use App\Support\Tenancy;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ResolveTenant
{
    public function __construct(protected Tenancy $tenancy)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        $central = config('tenancy.central_domain');
        $host = strtolower($request->getHost());

        // Tenant routes must never run on the central domain.
        if ($host === $central) {
            abort(404);
        }

        if (! str_ends_with($host, '.'.$central)) {
            abort(404); // custom domains are post-MVP
        }

        $slug = explode('.', $host)[0];

        if (in_array($slug, config('tenancy.reserved_slugs'), true)) {
            abort(404);
        }

        /** @var Tenant|null $tenant */
        $tenant = Tenant::query()->where('slug', $slug)->first();

        if (! $tenant) {
            abort(404, __('Clinic not found.'));
        }

        $this->tenancy->set($tenant);

        // Remove the implicit {tenant_slug} route parameter so controllers
        // and route-model binding never have to deal with it.
        $request->route()?->forgetParameter('tenant_slug');

        // Default the UI language to the clinic's locale unless the user chose one
        // (API requests are stateless — no session to consult).
        if (! $request->hasSession() || ! $request->session()->has('locale')) {
            app()->setLocale($tenant->default_locale);
        }

        return $next($request);
    }
}
