// Migration 004: Add usage_records table for detailed usage tracking.
// Idempotent — safe to run multiple times.
export default {
  version: 4,
  name: "usage-tracking",
  up(db) {
    // Create usage_records table
    db.exec(`
      CREATE TABLE IF NOT EXISTS usage_records (
        id TEXT PRIMARY KEY,
        userId TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
        apiKeyId TEXT REFERENCES apiKeys(id) ON DELETE SET NULL,
        model TEXT NOT NULL,
        inputTokens INTEGER DEFAULT 0,
        outputTokens INTEGER DEFAULT 0,
        totalTokens INTEGER DEFAULT 0,
        cost REAL DEFAULT 0,
        creditUsed REAL DEFAULT 0,
        status TEXT,
        errorMessage TEXT,
        endpoint TEXT,
        timestamp TEXT NOT NULL
      )
    `);

    // Create indexes
    db.exec(`CREATE INDEX IF NOT EXISTS idx_ur_user_ts ON usage_records(userId, timestamp)`);
    db.exec(`CREATE INDEX IF NOT EXISTS idx_ur_apikey_ts ON usage_records(apiKeyId, timestamp)`);
  },
};
