<?php

namespace App\Support;

use App\Models\User;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

class TenantAuth
{
    /**
     * Resolve the tenant admin user associated with the current request.
     *
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
    public static function resolveAdminUser(Request $request): User
    {
        $tenantId = $request->attributes->get('tenant_id')
            ?? $request->input('tenant_id')
            ?? $request->user()?->tenant_id;

        if (! $tenantId) {
            throw (new ModelNotFoundException)->setModel(User::class);
        }

        $user = $request->user();
        if ($user && in_array($user->role, ['tenant_admin', 'admin', 'super_admin', 'superadmin', 'member'], true)) {
            if (! $user->isSuperAdmin() || (int) $user->tenant_id === (int) $tenantId) {
                return $user;
            }
        }

        $user = User::query()
            ->where('tenant_id', $tenantId)
            ->whereIn('role', ['tenant_admin', 'admin', 'super_admin', 'superadmin', 'member'])
            ->orderByDesc('email_verified_at')
            ->orderBy('id')
            ->first();

        if (! $user) {
            throw (new ModelNotFoundException)->setModel(User::class);
        }

        return $user;
    }
}
