<?php

namespace App\Support;

use App\Models\Tenant;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class TenantRequestResolver
{
    public static function resolve(Request $request): Tenant
    {
        $tenant = $request->attributes->get('tenant');

        if ($tenant instanceof Tenant) {
            return $tenant;
        }

        $tenantId = $request->attributes->get('tenant_id')
            ?? $request->attributes->get('current_tenant_id')
            ?? $request->user()?->tenant_id;

        if ($tenantId) {
            $tenant = Tenant::query()->find($tenantId);

            if ($tenant) {
                $request->attributes->set('tenant', $tenant);

                return $tenant;
            }
        }

        throw new HttpResponseException(ApiError::response(
            'tenant_context_missing',
            'Tenant context missing',
            'Unable to determine tenant for the current request.',
            Response::HTTP_UNAUTHORIZED
        ));
    }
}
