-- اسکیمای اولیه حکم‌شو (SQLite)

CREATE TABLE IF NOT EXISTS users (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    mobile      TEXT    NOT NULL UNIQUE,
    first_name  TEXT,
    last_name   TEXT,
    avatar      TEXT,
    coins       INTEGER NOT NULL DEFAULT 0,
    is_admin    INTEGER NOT NULL DEFAULT 0,
    created_at  TEXT    NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS otp_tokens (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id     INTEGER NOT NULL,
    token       TEXT    NOT NULL,
    created_at  TEXT    NOT NULL DEFAULT (datetime('now')),
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_otp_user ON otp_tokens(user_id);

CREATE TABLE IF NOT EXISTS wallet_tx (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id     INTEGER NOT NULL,
    amount      INTEGER NOT NULL,        -- مثبت=واریز، منفی=برداشت
    reason      TEXT    NOT NULL,        -- مثل: game_win, kot, purchase
    ref         TEXT,                    -- شناسه میز/تراکنش مرجع
    created_at  TEXT    NOT NULL DEFAULT (datetime('now')),
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_wallet_user ON wallet_tx(user_id);

CREATE TABLE IF NOT EXISTS game_history (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    room         TEXT    NOT NULL,
    players_json TEXT    NOT NULL,
    winner_team  INTEGER NOT NULL,
    kot          INTEGER NOT NULL DEFAULT 0,
    created_at   TEXT    NOT NULL DEFAULT (datetime('now'))
);
