// Migration 002: Add users, rateLimits tables + userId FK to apiKeys.
// Idempotent — safe to run multiple times.
export default {
  version: 2,
  name: "users-and-rate-limits",
  up(db) {
    db.exec(`
      CREATE TABLE IF NOT EXISTS users (
        id TEXT PRIMARY KEY,
        username TEXT UNIQUE NOT NULL,
        password_hash TEXT NOT NULL,
        role TEXT DEFAULT 'user' CHECK(role IN ('admin','user')),
        is_active INTEGER DEFAULT 1,
        is_approved INTEGER DEFAULT 0,
        created_at TEXT DEFAULT (datetime('now'))
      )
    `);

    db.exec(`
      CREATE TABLE IF NOT EXISTS rateLimits (
        id TEXT PRIMARY KEY,
        userId TEXT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
        rtpMinute INTEGER DEFAULT 100,
        rtpDay INTEGER DEFAULT 100000,
        tokenLimitMonthly INTEGER DEFAULT 1000000,
        creditLimit REAL DEFAULT 5.0,
        maxConcurrent INTEGER DEFAULT 5,
        created_at TEXT DEFAULT (datetime('now')),
        updated_at TEXT DEFAULT (datetime('now'))
      )
    `);

    // Add userId column — safe re-run (SQLite ignores if exists error)
    try { db.exec(`ALTER TABLE apiKeys ADD COLUMN userId TEXT REFERENCES users(id) ON DELETE CASCADE`); } catch {}

    db.exec(`CREATE INDEX IF NOT EXISTS idx_users_username ON users(username)`);
    db.exec(`CREATE INDEX IF NOT EXISTS idx_rl_userId ON rateLimits(userId)`);
  },
};
