import time
from typing import Any, Dict, List, Optional, Tuple
import aiosqlite


DEFAULT_SERVICES = [
    ("WhatsApp", "🟢", 5.0, "WA"),
    ("Facebook", "🔵", 4.0, "NONE"),
    ("Instagram", "📸", 4.0, "NONE"),
    ("Telegram", "✈️", 6.0, "TG"),
]


class Database:
    def __init__(
        self,
        db_path: str,
        default_mask_text: str = "***",
        default_sms_url: str = "",
        default_sms_key: str = "",
    ):
        self.db_path = db_path
        self.default_mask_text = default_mask_text
        self.default_sms_url = default_sms_url
        self.default_sms_key = default_sms_key

    async def init(self) -> None:
        async with aiosqlite.connect(self.db_path) as db:
            await db.executescript(
                """
                PRAGMA journal_mode=WAL;

                CREATE TABLE IF NOT EXISTS settings (
                    key TEXT PRIMARY KEY,
                    value TEXT NOT NULL
                );

                CREATE TABLE IF NOT EXISTS sms_panels (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT UNIQUE NOT NULL,
                    api_url TEXT NOT NULL,
                    api_key TEXT DEFAULT '',
                    phone_field TEXT DEFAULT 'number',
                    sender_field TEXT DEFAULT 'sender',
                    text_field TEXT DEFAULT 'message',
                    data_key TEXT DEFAULT 'data',
                    is_active INTEGER DEFAULT 1,
                    created_at INTEGER NOT NULL
                );

                CREATE TABLE IF NOT EXISTS users (
                    telegram_id INTEGER PRIMARY KEY,
                    unique_id TEXT UNIQUE,
                    username TEXT,
                    full_name TEXT,
                    balance REAL DEFAULT 0.0,
                    total_otps INTEGER DEFAULT 0,
                    is_banned INTEGER DEFAULT 0,
                    is_verified_join INTEGER DEFAULT 0,
                    created_at INTEGER NOT NULL
                );

                CREATE TABLE IF NOT EXISTS required_joins (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    platform_type TEXT NOT NULL,
                    title TEXT NOT NULL,
                    url TEXT NOT NULL,
                    chat_id TEXT DEFAULT '',
                    is_active INTEGER DEFAULT 1,
                    created_at INTEGER NOT NULL
                );

                CREATE TABLE IF NOT EXISTS announcements (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    title TEXT NOT NULL,
                    body TEXT NOT NULL,
                    sent_count INTEGER DEFAULT 0,
                    created_at INTEGER NOT NULL
                );

                CREATE TABLE IF NOT EXISTS services (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT UNIQUE NOT NULL,
                    icon TEXT DEFAULT '📱',
                    rate_per_otp REAL DEFAULT 1.0,
                    checker_type TEXT DEFAULT 'NONE',
                    is_active INTEGER DEFAULT 1
                );

                CREATE TABLE IF NOT EXISTS numbers (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    phone_number TEXT NOT NULL,
                    service_id INTEGER NOT NULL,
                    iso_code TEXT NOT NULL,
                    country_flag TEXT DEFAULT '🌐',
                    checker_status TEXT DEFAULT 'UNCHECKED',
                    status TEXT DEFAULT 'AVAILABLE',
                    locked_by INTEGER,
                    locked_until INTEGER DEFAULT 0,
                    created_at INTEGER NOT NULL,
                    UNIQUE(phone_number, service_id),
                    FOREIGN KEY(service_id) REFERENCES services(id)
                );

                CREATE INDEX IF NOT EXISTS idx_numbers_pool
                ON numbers(service_id, iso_code, status);

                CREATE INDEX IF NOT EXISTS idx_numbers_prefix
                ON numbers(service_id, iso_code, phone_number);

                CREATE TABLE IF NOT EXISTS otp_logs (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    phone_number TEXT NOT NULL,
                    service_id INTEGER NOT NULL,
                    panel_name TEXT DEFAULT '',
                    otp_code TEXT NOT NULL,
                    sms_text TEXT NOT NULL,
                    sms_language TEXT DEFAULT 'Unknown',
                    user_id INTEGER,
                    earned_amount REAL DEFAULT 0.0,
                    sms_hash TEXT UNIQUE NOT NULL,
                    created_at INTEGER NOT NULL
                );

                CREATE TABLE IF NOT EXISTS checker_accounts (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    platform TEXT NOT NULL,
                    label TEXT NOT NULL,
                    credential TEXT NOT NULL,
                    is_active INTEGER DEFAULT 1,
                    created_at INTEGER NOT NULL
                );

                CREATE TABLE IF NOT EXISTS withdrawals (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    user_id INTEGER NOT NULL,
                    amount REAL NOT NULL,
                    method TEXT NOT NULL,
                    wallet_address TEXT NOT NULL,
                    status TEXT DEFAULT 'PENDING',
                    created_at INTEGER NOT NULL
                );
                """
            )
            await db.execute(
                "INSERT OR IGNORE INTO settings (key, value) VALUES ('mask_replacement', ?)",
                (self.default_mask_text,),
            )
            if self.default_sms_url:
                await db.execute(
                    """
                    INSERT OR IGNORE INTO sms_panels (name, api_url, api_key, is_active, created_at)
                    VALUES ('Default Panel', ?, ?, 1, ?)
                    """,
                    (self.default_sms_url, self.default_sms_key, int(time.time())),
                )
            for name, icon, rate, checker_type in DEFAULT_SERVICES:
                await db.execute(
                    """
                    INSERT OR IGNORE INTO services (name, icon, rate_per_otp, checker_type, is_active)
                    VALUES (?, ?, ?, ?, 1)
                    """,
                    (name, icon, rate, checker_type),
                )
            await db.commit()

    # ---------- Multi-SMS Panel CRUD ----------
    async def add_sms_panel(
        self,
        name: str,
        api_url: str,
        api_key: str = "",
        phone_field: str = "number",
        sender_field: str = "sender",
        text_field: str = "message",
        data_key: str = "data",
    ) -> int:
        now = int(time.time())
        async with aiosqlite.connect(self.db_path) as db:
            cur = await db.execute(
                """
                INSERT INTO sms_panels
                (name, api_url, api_key, phone_field, sender_field, text_field, data_key, is_active, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?)
                """,
                (
                    name.strip(),
                    api_url.strip(),
                    api_key.strip(),
                    phone_field.strip() or "number",
                    sender_field.strip() or "sender",
                    text_field.strip() or "message",
                    data_key.strip(),
                    now,
                ),
            )
            await db.commit()
            return cur.lastrowid

    async def get_all_sms_panels(self) -> List[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute("SELECT * FROM sms_panels ORDER BY id ASC")
            return [dict(r) for r in await cur.fetchall()]

    async def get_active_sms_panels(self) -> List[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute("SELECT * FROM sms_panels WHERE is_active = 1 ORDER BY id ASC")
            return [dict(r) for r in await cur.fetchall()]

    async def toggle_sms_panel(self, panel_id: int) -> Optional[int]:
        async with aiosqlite.connect(self.db_path) as db:
            cur = await db.execute("SELECT is_active FROM sms_panels WHERE id = ?", (panel_id,))
            row = await cur.fetchone()
            if not row:
                return None
            new_state = 0 if row[0] else 1
            await db.execute("UPDATE sms_panels SET is_active = ? WHERE id = ?", (new_state, panel_id))
            await db.commit()
            return new_state

    async def delete_sms_panel(self, panel_id: int) -> None:
        async with aiosqlite.connect(self.db_path) as db:
            await db.execute("DELETE FROM sms_panels WHERE id = ?", (panel_id,))
            await db.commit()

    # ---------- Settings (Custom 3-Digit Mask Text) ----------
    async def get_setting(self, key: str, default: str = "") -> str:
        async with aiosqlite.connect(self.db_path) as db:
            cur = await db.execute("SELECT value FROM settings WHERE key = ?", (key,))
            row = await cur.fetchone()
            return row[0] if row else default

    async def set_setting(self, key: str, value: str) -> None:
        async with aiosqlite.connect(self.db_path) as db:
            await db.execute(
                """
                INSERT INTO settings (key, value) VALUES (?, ?)
                ON CONFLICT(key) DO UPDATE SET value = excluded.value
                """,
                (key, value),
            )
            await db.commit()

    # ---------- Users ----------
    async def upsert_user(self, telegram_id: int, username: str, full_name: str) -> str:
        now = int(time.time())
        async with aiosqlite.connect(self.db_path) as db:
            cur = await db.execute("SELECT unique_id FROM users WHERE telegram_id = ?", (telegram_id,))
            existing = await cur.fetchone()
            if existing and existing[0]:
                await db.execute(
                    "UPDATE users SET username = ?, full_name = ? WHERE telegram_id = ?",
                    (username or "", full_name or "", telegram_id),
                )
                await db.commit()
                return existing[0]

            cnt_cur = await db.execute("SELECT COUNT(*) FROM users")
            seq = (await cnt_cur.fetchone())[0] + 10001
            unique_id = f"UID-{seq}"
            await db.execute(
                """
                INSERT INTO users (telegram_id, unique_id, username, full_name, created_at)
                VALUES (?, ?, ?, ?, ?)
                ON CONFLICT(telegram_id) DO UPDATE SET
                    username = excluded.username,
                    full_name = excluded.full_name
                """,
                (telegram_id, unique_id, username or "", full_name or "", now),
            )
            await db.commit()
            return unique_id

    async def get_user_by_unique_id(self, unique_id: str) -> Optional[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute(
                "SELECT * FROM users WHERE LOWER(unique_id) = LOWER(?)",
                (unique_id.strip(),),
            )
            row = await cur.fetchone()
            return dict(row) if row else None

    async def set_user_banned(self, telegram_id: int, banned: bool) -> None:
        async with aiosqlite.connect(self.db_path) as db:
            await db.execute(
                "UPDATE users SET is_banned = ? WHERE telegram_id = ?",
                (1 if banned else 0, telegram_id),
            )
            await db.commit()

    async def set_user_verified_join(self, telegram_id: int, verified: bool) -> None:
        async with aiosqlite.connect(self.db_path) as db:
            await db.execute(
                "UPDATE users SET is_verified_join = ? WHERE telegram_id = ?",
                (1 if verified else 0, telegram_id),
            )
            await db.commit()

    # ---------- Force-Join Requirements ----------
    async def add_required_join(
        self, platform_type: str, title: str, url: str, chat_id: str = ""
    ) -> int:
        now = int(time.time())
        async with aiosqlite.connect(self.db_path) as db:
            cur = await db.execute(
                """
                INSERT INTO required_joins (platform_type, title, url, chat_id, is_active, created_at)
                VALUES (?, ?, ?, ?, 1, ?)
                """,
                (platform_type.upper(), title.strip(), url.strip(), chat_id.strip(), now),
            )
            # Reset verification so existing users must also join newly added groups/channels
            await db.execute("UPDATE users SET is_verified_join = 0")
            await db.commit()
            return cur.lastrowid

    async def get_active_required_joins(self) -> List[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute("SELECT * FROM required_joins WHERE is_active = 1 ORDER BY id ASC")
            return [dict(r) for r in await cur.fetchall()]

    async def get_all_required_joins(self) -> List[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute("SELECT * FROM required_joins ORDER BY id ASC")
            return [dict(r) for r in await cur.fetchall()]

    async def delete_required_join(self, join_id: int) -> None:
        async with aiosqlite.connect(self.db_path) as db:
            await db.execute("DELETE FROM required_joins WHERE id = ?", (join_id,))
            await db.commit()

    # ---------- Announcements ----------
    async def log_announcement(self, title: str, body: str, sent_count: int) -> int:
        now = int(time.time())
        async with aiosqlite.connect(self.db_path) as db:
            cur = await db.execute(
                """
                INSERT INTO announcements (title, body, sent_count, created_at)
                VALUES (?, ?, ?, ?)
                """,
                (title.strip(), body.strip(), sent_count, now),
            )
            await db.commit()
            return cur.lastrowid

    async def get_user(self, telegram_id: int) -> Optional[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute("SELECT * FROM users WHERE telegram_id = ?", (telegram_id,))
            row = await cur.fetchone()
            return dict(row) if row else None

    async def get_all_user_ids(self) -> List[int]:
        async with aiosqlite.connect(self.db_path) as db:
            cur = await db.execute("SELECT telegram_id FROM users WHERE is_banned = 0")
            rows = await cur.fetchall()
            return [r[0] for r in rows]

    # ---------- Services ----------
    async def get_active_services(self) -> List[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute("SELECT * FROM services WHERE is_active = 1 ORDER BY id ASC")
            return [dict(r) for r in await cur.fetchall()]

    async def get_all_services(self) -> List[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute("SELECT * FROM services ORDER BY id ASC")
            return [dict(r) for r in await cur.fetchall()]

    async def get_service(self, service_id: int) -> Optional[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute("SELECT * FROM services WHERE id = ?", (service_id,))
            row = await cur.fetchone()
            return dict(row) if row else None

    async def add_service(self, name: str, icon: str, rate: float, checker_type: str) -> int:
        async with aiosqlite.connect(self.db_path) as db:
            cur = await db.execute(
                """
                INSERT INTO services (name, icon, rate_per_otp, checker_type, is_active)
                VALUES (?, ?, ?, ?, 1)
                """,
                (name.strip(), icon.strip() or "📱", rate, checker_type.upper()),
            )
            await db.commit()
            return cur.lastrowid

    # ---------- Number Pool, Prefix Filter & 4-Number Batch Logic ----------
    async def bulk_insert_numbers(
        self,
        service_id: int,
        rows: List[Tuple[str, str, str, str, str]],
    ) -> Tuple[int, int]:
        now = int(time.time())
        inserted = 0
        duplicates = 0
        async with aiosqlite.connect(self.db_path) as db:
            for phone, iso, flag, checker_status, status in rows:
                cur = await db.execute(
                    """
                    INSERT OR IGNORE INTO numbers
                    (phone_number, service_id, iso_code, country_flag, checker_status, status, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                    """,
                    (phone, service_id, iso, flag, checker_status, status, now),
                )
                if cur.rowcount > 0:
                    inserted += 1
                else:
                    duplicates += 1
            await db.commit()
        return inserted, duplicates

    async def release_expired_locks(self) -> int:
        now = int(time.time())
        async with aiosqlite.connect(self.db_path) as db:
            cur = await db.execute(
                """
                UPDATE numbers
                SET status = 'AVAILABLE', locked_by = NULL, locked_until = 0
                WHERE status = 'LOCKED' AND locked_until > 0 AND locked_until <= ?
                """,
                (now,),
            )
            await db.commit()
            return cur.rowcount

    async def get_available_countries(self, service_id: int) -> List[Dict[str, Any]]:
        await self.release_expired_locks()
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute(
                """
                SELECT iso_code, country_flag, COUNT(*) as available_count
                FROM numbers
                WHERE service_id = ? AND status = 'AVAILABLE'
                GROUP BY iso_code, country_flag
                ORDER BY available_count DESC
                """,
                (service_id,),
            )
            return [dict(r) for r in await cur.fetchall()]

    async def count_prefix_matches(self, service_id: int, iso_code: str, prefix_digits: str) -> int:
        await self.release_expired_locks()
        like_pattern = f"+{prefix_digits}%"
        async with aiosqlite.connect(self.db_path) as db:
            cur = await db.execute(
                """
                SELECT COUNT(*) FROM numbers
                WHERE service_id = ? AND iso_code = ? AND status = 'AVAILABLE'
                  AND (phone_number LIKE ? OR REPLACE(phone_number, '+', '') LIKE ?)
                """,
                (service_id, iso_code, like_pattern, f"{prefix_digits}%"),
            )
            return (await cur.fetchone())[0]

    async def allocate_batch(
        self,
        user_id: int,
        service_id: int,
        iso_code: str,
        batch_size: int = 4,
        lock_minutes: int = 15,
        prefix_digits: str = "",
    ) -> List[Dict[str, Any]]:
        now = int(time.time())
        lock_until = now + (lock_minutes * 60)

        prefix_clause = ""
        prefix_params: List[Any] = []
        if prefix_digits:
            prefix_clause = " AND (phone_number LIKE ? OR REPLACE(phone_number, '+', '') LIKE ?)"
            prefix_params = [f"+{prefix_digits}%", f"{prefix_digits}%"]

        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            await db.execute(
                """
                UPDATE numbers
                SET status = 'AVAILABLE', locked_by = NULL, locked_until = 0
                WHERE status = 'LOCKED' AND locked_until <= ?
                """,
                (now,),
            )

            prev_cur = await db.execute(
                """
                SELECT id FROM numbers
                WHERE locked_by = ? AND service_id = ? AND iso_code = ? AND status = 'LOCKED'
                """,
                (user_id, service_id, iso_code),
            )
            prev_ids = [r["id"] for r in await prev_cur.fetchall()]

            if prev_ids:
                placeholders = ",".join("?" for _ in prev_ids)
                await db.execute(
                    f"""
                    UPDATE numbers
                    SET status = 'AVAILABLE', locked_by = NULL, locked_until = 0
                    WHERE id IN ({placeholders})
                    """,
                    prev_ids,
                )

            if prev_ids:
                placeholders = ",".join("?" for _ in prev_ids)
                cur = await db.execute(
                    f"""
                    SELECT * FROM numbers
                    WHERE service_id = ? AND iso_code = ? AND status = 'AVAILABLE'
                      {prefix_clause}
                      AND id NOT IN ({placeholders})
                    ORDER BY RANDOM()
                    LIMIT ?
                    """,
                    [service_id, iso_code, *prefix_params, *prev_ids, batch_size],
                )
                picked = [dict(r) for r in await cur.fetchall()]
            else:
                picked = []

            if len(picked) < batch_size:
                cur = await db.execute(
                    f"""
                    SELECT * FROM numbers
                    WHERE service_id = ? AND iso_code = ? AND status = 'AVAILABLE'
                      {prefix_clause}
                    ORDER BY RANDOM()
                    LIMIT ?
                    """,
                    [service_id, iso_code, *prefix_params, batch_size],
                )
                picked = [dict(r) for r in await cur.fetchall()]

            if picked:
                picked_ids = [r["id"] for r in picked]
                placeholders = ",".join("?" for _ in picked_ids)
                await db.execute(
                    f"""
                    UPDATE numbers
                    SET status = 'LOCKED', locked_by = ?, locked_until = ?
                    WHERE id IN ({placeholders})
                    """,
                    [user_id, lock_until, *picked_ids],
                )

            await db.commit()
            return picked

    # ---------- OTP Recording & Per-OTP Income ----------
    async def process_incoming_otp(
        self,
        phone_number: str,
        service_hint: str,
        otp_code: str,
        sms_text: str,
        sms_language: str,
        sms_hash: str,
        panel_name: str = "",
    ) -> Optional[Dict[str, Any]]:
        now = int(time.time())
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row

            dup = await db.execute("SELECT id FROM otp_logs WHERE sms_hash = ?", (sms_hash,))
            if await dup.fetchone():
                return None

            cur = await db.execute(
                """
                SELECT n.*, s.name AS service_name, s.icon AS service_icon, s.rate_per_otp
                FROM numbers n
                JOIN services s ON s.id = n.service_id
                WHERE n.phone_number = ? AND n.status IN ('LOCKED', 'USED')
                ORDER BY
                    CASE WHEN LOWER(s.name) = LOWER(?) THEN 0 ELSE 1 END,
                    CASE WHEN n.status = 'LOCKED' THEN 0 ELSE 1 END,
                    n.locked_until DESC
                LIMIT 1
                """,
                (phone_number, service_hint or ""),
            )
            match = await cur.fetchone()
            if not match:
                return None

            match_dict = dict(match)
            user_id = match_dict["locked_by"]
            earned = float(match_dict["rate_per_otp"]) if user_id else 0.0

            await db.execute(
                """
                INSERT INTO otp_logs
                (phone_number, service_id, panel_name, otp_code, sms_text, sms_language, user_id, earned_amount, sms_hash, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """,
                (
                    phone_number,
                    match_dict["service_id"],
                    panel_name,
                    otp_code,
                    sms_text,
                    sms_language,
                    user_id,
                    earned,
                    sms_hash,
                    now,
                ),
            )

            await db.execute("UPDATE numbers SET status = 'USED' WHERE id = ?", (match_dict["id"],))

            if user_id:
                await db.execute(
                    """
                    UPDATE users
                    SET balance = balance + ?, total_otps = total_otps + 1
                    WHERE telegram_id = ?
                    """,
                    (earned, user_id),
                )

            await db.commit()
            match_dict["earned_amount"] = earned
            match_dict["otp_code"] = otp_code
            match_dict["sms_text"] = sms_text
            match_dict["sms_language"] = sms_language
            match_dict["panel_name"] = panel_name
            return match_dict

    async def get_user_otp_history(self, user_id: int, limit: int = 10) -> List[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute(
                """
                SELECT o.*, s.name AS service_name, s.icon AS service_icon
                FROM otp_logs o
                JOIN services s ON s.id = o.service_id
                WHERE o.user_id = ?
                ORDER BY o.created_at DESC
                LIMIT ?
                """,
                (user_id, limit),
            )
            return [dict(r) for r in await cur.fetchall()]

    # ---------- Checker Accounts ----------
    async def add_checker_account(self, platform: str, label: str, credential: str) -> int:
        now = int(time.time())
        async with aiosqlite.connect(self.db_path) as db:
            cur = await db.execute(
                """
                INSERT INTO checker_accounts (platform, label, credential, is_active, created_at)
                VALUES (?, ?, ?, 1, ?)
                """,
                (platform.upper(), label.strip(), credential.strip(), now),
            )
            await db.commit()
            return cur.lastrowid

    async def get_active_checker_accounts(self, platform: str) -> List[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute(
                "SELECT * FROM checker_accounts WHERE platform = ? AND is_active = 1",
                (platform.upper(),),
            )
            return [dict(r) for r in await cur.fetchall()]

    # ---------- Withdrawals & Stats ----------
    async def create_withdrawal(
        self, user_id: int, amount: float, method: str, wallet_address: str
    ) -> Optional[int]:
        now = int(time.time())
        async with aiosqlite.connect(self.db_path) as db:
            cur = await db.execute("SELECT balance FROM users WHERE telegram_id = ?", (user_id,))
            row = await cur.fetchone()
            if not row or row[0] < amount:
                return None
            await db.execute(
                "UPDATE users SET balance = balance - ? WHERE telegram_id = ?",
                (amount, user_id),
            )
            w_cur = await db.execute(
                """
                INSERT INTO withdrawals (user_id, amount, method, wallet_address, status, created_at)
                VALUES (?, ?, ?, ?, 'PENDING', ?)
                """,
                (user_id, amount, method, wallet_address, now),
            )
            await db.commit()
            return w_cur.lastrowid

    async def get_pending_withdrawals(self) -> List[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute(
                "SELECT * FROM withdrawals WHERE status = 'PENDING' ORDER BY created_at ASC"
            )
            return [dict(r) for r in await cur.fetchall()]

    async def update_withdrawal_status(self, withdrawal_id: int, new_status: str) -> Optional[Dict[str, Any]]:
        async with aiosqlite.connect(self.db_path) as db:
            db.row_factory = aiosqlite.Row
            cur = await db.execute("SELECT * FROM withdrawals WHERE id = ?", (withdrawal_id,))
            row = await cur.fetchone()
            if not row or row["status"] != "PENDING":
                return None
            await db.execute(
                "UPDATE withdrawals SET status = ? WHERE id = ?",
                (new_status, withdrawal_id),
            )
            if new_status == "REJECTED":
                await db.execute(
                    "UPDATE users SET balance = balance + ? WHERE telegram_id = ?",
                    (row["amount"], row["user_id"]),
                )
            await db.commit()
            return dict(row)

    async def get_stats(self) -> Dict[str, Any]:
        async with aiosqlite.connect(self.db_path) as db:
            stats = {}
            for key, query in [
                ("users", "SELECT COUNT(*) FROM users"),
                ("active_panels", "SELECT COUNT(*) FROM sms_panels WHERE is_active = 1"),
                ("available_numbers", "SELECT COUNT(*) FROM numbers WHERE status = 'AVAILABLE'"),
                ("locked_numbers", "SELECT COUNT(*) FROM numbers WHERE status = 'LOCKED'"),
                ("used_numbers", "SELECT COUNT(*) FROM numbers WHERE status = 'USED'"),
                ("total_otps", "SELECT COUNT(*) FROM otp_logs"),
                ("pending_withdrawals", "SELECT COUNT(*) FROM withdrawals WHERE status = 'PENDING'"),
            ]:
                cur = await db.execute(query)
                stats[key] = (await cur.fetchone())[0]
            return stats
