// Migration 003: Add packages and userPackages tables, extend apiKeys with RTK/Caveman columns.
// Idempotent — safe to run multiple times.
export default {
  version: 3,
  name: "packages-per-key-settings",
  up(db) {
    // Create packages table
    db.exec(`
      CREATE TABLE IF NOT EXISTS packages (
        id TEXT PRIMARY KEY,
        name TEXT UNIQUE,
        description TEXT,
        rtpMinute INTEGER,
        rtpDay INTEGER,
        tokenLimitMonthly INTEGER,
        creditLimit REAL,
        creditToTokenRatio REAL DEFAULT 1000,
        maxConcurrent INTEGER,
        durationDays INTEGER,
        price REAL DEFAULT 0,
        isActive INTEGER DEFAULT 1,
        createdAt TEXT,
        updatedAt TEXT
      )
    `);

    // Create userPackages table
    db.exec(`
      CREATE TABLE IF NOT EXISTS userPackages (
        id TEXT PRIMARY KEY,
        userId TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
        packageId TEXT REFERENCES packages(id) ON DELETE SET NULL,
        rtpMinuteOverride INTEGER,
        rtpDayOverride INTEGER,
        tokenLimitMonthlyOverride INTEGER,
        creditLimitOverride REAL,
        maxConcurrentOverride INTEGER,
        assignedAt TEXT,
        expiresAt TEXT,
        UNIQUE(userId)
      )
    `);

    // Add per-key RTK/Caveman columns to apiKeys
    try {
      db.exec(`ALTER TABLE apiKeys ADD COLUMN rtkEnabled INTEGER NULL`);
    } catch {}
    try {
      db.exec(`ALTER TABLE apiKeys ADD COLUMN cavemanEnabled INTEGER NULL`);
    } catch {}
    try {
      db.exec(`ALTER TABLE apiKeys ADD COLUMN cavemanLevel TEXT NULL`);
    } catch {}

    // Create indexes
    db.exec(`CREATE INDEX IF NOT EXISTS idx_packages_name ON packages(name)`);
    db.exec(`CREATE INDEX IF NOT EXISTS idx_up_userId ON userPackages(userId)`);
    db.exec(`CREATE INDEX IF NOT EXISTS idx_up_packageId ON userPackages(packageId)`);

    // Seed default packages (idempotent)
    db.exec(`
      INSERT OR IGNORE INTO packages (id, name, description, rtpMinute, rtpDay, tokenLimitMonthly, creditLimit, creditToTokenRatio, maxConcurrent, durationDays, price, isActive, createdAt, updatedAt) VALUES
      ('pkg-free', 'Free', 'Free tier', 100, 10000, 100000, 100, 1000, 3, null, 0, 1, datetime('now'), datetime('now')),
      ('pkg-basic', 'Basic', 'Basic tier', 200, 50000, 500000, 500, 1000, 5, 30, 9.99, 1, datetime('now'), datetime('now')),
      ('pkg-pro', 'Pro', 'Pro tier', 500, 200000, 2000000, 2000, 1000, 10, 30, 29.99, 1, datetime('now'), datetime('now')),
      ('pkg-enterprise', 'Enterprise', 'Enterprise tier', 1000, 500000, 10000000, 10000, 1000, 20, 365, 99.99, 1, datetime('now'), datetime('now'))
    `);
  },
};
