<?php
declare(strict_types=1);

final class Auth
{
    public static function start(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    public static function loginWithTelegram(Repository $repo, array $config, string $initData): array
    {
        self::start();
        $tgUser = Security::verifyTelegramInitData($initData, (string)$config['main_bot_token']);
        $user = $repo->upsertUser([
            'telegram_id' => (string)$tgUser['id'],
            'username' => $tgUser['username'] ?? null,
            'first_name' => $tgUser['first_name'] ?? null,
            'last_name' => $tgUser['last_name'] ?? null,
        ]);
        $_SESSION['uid'] = (int)$user['id'];
        return $user;
    }

    public static function loginWithPanelKey(Repository $repo, array $config, string $key, string|int $telegramId): array
    {
        self::start();
        $expected = (string)($config['panel_login_key'] ?? '');
        if ($expected === '' || !hash_equals($expected, $key)) {
            throw new RuntimeException('کلید ورود پنل اشتباه است.');
        }
        $tid = digits_only((string)$telegramId);
        $allowed = array_map('strval', $config['super_admin_ids'] ?? []);
        if (!in_array($tid, $allowed, true)) {
            throw new RuntimeException('این آیدی جزو ادمین اصلی نصب نیست.');
        }
        $user = $repo->makeAdmin($tid, 'super');
        $_SESSION['uid'] = (int)$user['id'];
        return $user;
    }

    public static function user(Repository $repo): ?array
    {
        self::start();
        $uid = (int)($_SESSION['uid'] ?? 0);
        if ($uid <= 0) return null;
        return $repo->findUserById($uid);
    }

    public static function requireUser(Repository $repo): array
    {
        $u = self::user($repo);
        if (!$u) json_response(['ok' => false, 'error' => 'ابتدا وارد پنل شوید.'], 401);
        if (($u['status'] ?? '') !== 'active') json_response(['ok' => false, 'error' => 'حساب شما مسدود است.'], 403);
        return $u;
    }

    public static function requireAdmin(Repository $repo): array
    {
        $u = self::requireUser($repo);
        if (($u['role'] ?? '') !== 'admin') json_response(['ok' => false, 'error' => 'دسترسی ادمین لازم است.'], 403);
        return $u;
    }

    public static function requireAdminOrReseller(Repository $repo): array
    {
        $u = self::requireUser($repo);
        if (!in_array($u['role'] ?? '', ['admin','reseller'], true)) json_response(['ok' => false, 'error' => 'دسترسی ادمین یا نماینده لازم است.'], 403);
        return $u;
    }
}
