-- ============================================================================
-- Telegram Multi-Panel SMS/OTP Bot — Complete Database Schema (SQLite 3)
-- Compatible with: Python (aiogram 3 + aiosqlite) & Web Admin Panel
-- ============================================================================

PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;

-- ----------------------------------------------------------------------------
-- 1. Global Bot & OTP Group Settings (3-Digit Custom Mask, Batch Size, Lock)
-- ----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS settings (
    key         TEXT PRIMARY KEY,
    value       TEXT NOT NULL,
    updated_at  INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

-- ----------------------------------------------------------------------------
-- 2. Multiple SMS Panel APIs (All active panels feed into the same OTP Group)
-- ----------------------------------------------------------------------------
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 NOT NULL DEFAULT 'number',
    sender_field  TEXT NOT NULL DEFAULT 'sender',
    text_field    TEXT NOT NULL DEFAULT 'message',
    data_key      TEXT NOT NULL DEFAULT 'data',
    poll_interval INTEGER NOT NULL DEFAULT 5,
    is_active     INTEGER NOT NULL DEFAULT 1 CHECK (is_active IN (0, 1)),
    created_at    INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

-- ----------------------------------------------------------------------------
-- 3. Users (Permanent Unique ID, Registration Date, Balance, Block & Join Gate)
-- ----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS users (
    telegram_id      INTEGER PRIMARY KEY,
    unique_id        TEXT UNIQUE NOT NULL,         -- e.g. UID-10001
    username         TEXT DEFAULT '',
    full_name        TEXT DEFAULT '',
    balance          REAL NOT NULL DEFAULT 0.0,
    total_otps       INTEGER NOT NULL DEFAULT 0,
    is_banned        INTEGER NOT NULL DEFAULT 0 CHECK (is_banned IN (0, 1)),
    is_verified_join INTEGER NOT NULL DEFAULT 0 CHECK (is_verified_join IN (0, 1)),
    created_at       INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

CREATE INDEX IF NOT EXISTS idx_users_unique_id ON users(unique_id);
CREATE INDEX IF NOT EXISTS idx_users_banned    ON users(is_banned);

-- ----------------------------------------------------------------------------
-- 4. Mandatory Force-Join Links (Telegram Channels, YouTube, OTP & Backup Groups)
-- ----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS required_joins (
    id            INTEGER PRIMARY KEY AUTOINCREMENT,
    platform_type TEXT NOT NULL CHECK (platform_type IN ('TG_CHANNEL', 'OTP_GROUP', 'BACKUP_GROUP', 'YOUTUBE')),
    title         TEXT NOT NULL,
    url           TEXT NOT NULL,
    chat_id       TEXT DEFAULT '',                 -- @username or -100... for live get_chat_member check
    is_active     INTEGER NOT NULL DEFAULT 1 CHECK (is_active IN (0, 1)),
    created_at    INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

CREATE INDEX IF NOT EXISTS idx_required_joins_active ON required_joins(is_active);

-- ----------------------------------------------------------------------------
-- 5. Services / Apps / Websites (WhatsApp, Facebook, Instagram, Telegram, etc.)
-- ----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS services (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    name         TEXT UNIQUE NOT NULL,
    icon         TEXT NOT NULL DEFAULT '📱',
    rate_per_otp REAL NOT NULL DEFAULT 1.0,
    checker_type TEXT NOT NULL DEFAULT 'NONE' CHECK (checker_type IN ('NONE', 'WA', 'TG')),
    is_active    INTEGER NOT NULL DEFAULT 1 CHECK (is_active IN (0, 1))
);

-- ----------------------------------------------------------------------------
-- 6. Service-Specific Number Pool (4-Number Batching, Prefix Filter & Auto-Lock)
-- ----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS numbers (
    id             INTEGER PRIMARY KEY AUTOINCREMENT,
    phone_number   TEXT NOT NULL,                  -- E.164 format, e.g. +8801712345678
    service_id     INTEGER NOT NULL,
    iso_code       TEXT NOT NULL,                  -- 2-letter ISO code, e.g. BD, YE, US
    country_flag   TEXT NOT NULL DEFAULT '🌐',
    checker_status TEXT NOT NULL DEFAULT 'UNCHECKED' CHECK (checker_status IN ('UNCHECKED', 'FRESH', 'REGISTERED')),
    status         TEXT NOT NULL DEFAULT 'AVAILABLE' CHECK (status IN ('AVAILABLE', 'LOCKED', 'USED', 'INVALID')),
    locked_by      INTEGER,
    locked_until   INTEGER NOT NULL DEFAULT 0,
    created_at     INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
    UNIQUE (phone_number, service_id),
    FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE,
    FOREIGN KEY (locked_by)  REFERENCES users(telegram_id) ON DELETE SET NULL
);

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 INDEX IF NOT EXISTS idx_numbers_lock     ON numbers(status, locked_until);
CREATE INDEX IF NOT EXISTS idx_numbers_phone    ON numbers(phone_number);

-- ----------------------------------------------------------------------------
-- 7. Received OTP Logs (Multi-Panel Source, Language Detection & Anti-Duplicate)
-- ----------------------------------------------------------------------------
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 NOT NULL DEFAULT 'Unknown', -- e.g. English, Bengali (বাংলা), Arabic (العربية)
    user_id       INTEGER,
    earned_amount REAL NOT NULL DEFAULT 0.0,
    sms_hash      TEXT UNIQUE NOT NULL,            -- SHA-256 hash preventing duplicate credit
    created_at    INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
    FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id)    REFERENCES users(telegram_id) ON DELETE SET NULL
);

CREATE INDEX IF NOT EXISTS idx_otp_logs_user ON otp_logs(user_id, created_at DESC);

-- ----------------------------------------------------------------------------
-- 8. WhatsApp & Telegram Auto-Checker Accounts
-- ----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS checker_accounts (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    platform   TEXT NOT NULL CHECK (platform IN ('WA', 'TG')),
    label      TEXT NOT NULL,
    credential TEXT NOT NULL,                      -- WAHA/Baileys session name or Telethon StringSession
    is_active  INTEGER NOT NULL DEFAULT 1 CHECK (is_active IN (0, 1)),
    created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

-- ----------------------------------------------------------------------------
-- 9. User Withdrawal Requests (Approve / Reject with Auto-Refund)
-- ----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS withdrawals (
    id             INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id        INTEGER NOT NULL,
    amount         REAL NOT NULL CHECK (amount > 0),
    method         TEXT NOT NULL,                  -- e.g. bKash, Nagad, Binance USDT
    wallet_address TEXT NOT NULL,
    status         TEXT NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING', 'APPROVED', 'REJECTED')),
    created_at     INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
    FOREIGN KEY (user_id) REFERENCES users(telegram_id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_withdrawals_status ON withdrawals(status, created_at ASC);

-- ----------------------------------------------------------------------------
-- 10. Admin Global Announcements History
-- ----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS announcements (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    title      TEXT NOT NULL,
    body       TEXT NOT NULL,
    sent_count INTEGER NOT NULL DEFAULT 0,
    created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

-- ============================================================================
-- Default Seed Data
-- ============================================================================
INSERT OR IGNORE INTO settings (key, value) VALUES
    ('mask_replacement', '***'),
    ('batch_size', '4'),
    ('lock_minutes', '15'),
    ('refresh_cooldown_seconds', '8'),
    ('min_withdraw_amount', '50.0');

INSERT OR IGNORE INTO services (name, icon, rate_per_otp, checker_type, is_active) VALUES
    ('WhatsApp',  '🟢', 5.0, 'WA',   1),
    ('Facebook',  '🔵', 4.0, 'NONE', 1),
    ('Instagram', '📸', 4.0, 'NONE', 1),
    ('Telegram',  '✈️', 6.0, 'TG',   1);
