<?php

namespace App\Http\Middleware;

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

/**
 * Resolves which hotel (tenant) this request belongs to:
 *  - /platform/* runs unscoped (the platform owner sees everything).
 *  - Super admins act on the hotel they picked in the platform panel.
 *  - Staff always operate on their own hotel.
 *  - Public/guest traffic maps by custom domain or subdomain slug,
 *    falling back to the flagship (first) hotel — which is what
 *    localhost resolves to in development.
 */
class ResolveHotel
{
    public function handle(Request $request, Closure $next): Response
    {
        rescue(function () use ($request) {
            if ($request->is('platform*') || $request->is('billing/*')) {
                return; // unscoped
            }

            $user = $request->user();

            if ($user && $user->role === 'super_admin') {
                if ($actingId = session('acting_hotel_id')) {
                    Tenancy::set(Hotel::find($actingId));
                }

                return;
            }

            if ($user && $user->hotel_id && $user->isStaff()) {
                Tenancy::set(Hotel::find($user->hotel_id));

                return;
            }

            $host = $request->getHost();
            $subdomain = explode('.', $host)[0];

            Tenancy::set(
                Hotel::where('domain', $host)->orWhere('slug', $subdomain)->first()
                    ?? Hotel::orderBy('id')->first()
            );
        }, report: false);

        return $next($request);
    }
}
