<?php

declare(strict_types=1);

namespace Maestro\Core\Support;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as FrameworkUser;
use Maestro\Core\Database\Seeders\UserSeeder;
use Spatie\Permission\Traits\HasRoles;

/**
 * Resolves the host application's User Eloquent class from auth config.
 * Must match {@see UserSeeder} so Spatie morph types stay consistent.
 */
final class AuthUserResolver
{
    /**
     * @return class-string<Authenticatable&Model>
     */
    public static function eloquentModelClass(): string
    {
        /** @var mixed $configured */
        $configured = config('auth.providers.users.model');

        $class = is_string($configured) ? $configured : null;

        if ($class === null || ! class_exists($class)) {
            throw new \LogicException('auth.providers.users.model must name an existing User class for Maestro CORE.');
        }

        $usesHasRoles = in_array(
            HasRoles::class,
            class_uses_recursive($class),
            true,
        );

        if (! is_subclass_of($class, FrameworkUser::class) || ! $usesHasRoles) {
            throw new \LogicException(sprintf(
                'Maestro CORE requires `%s` to extend `%s` and use `%s`. Run `php artisan core:install` or extend `Maestro\\Core\\Models\\User`.',
                $class,
                FrameworkUser::class,
                HasRoles::class,
            ));
        }

        return $class;
    }
}
