const jwt = require('jsonwebtoken');
const db = require('../../backend/database');

function getAuthToken() {
  return jwt.sign({ role: 'admin', name: 'TestAdmin' }, process.env.JWT_SECRET, { expiresIn: '1h' });
}

function getAuthHeader() {
  return `Bearer ${getAuthToken()}`;
}

function cleanDb() {
  db.exec('DELETE FROM live_votes');
  db.exec('DELETE FROM chat_logs');
  db.exec('DELETE FROM session_games');
  db.exec('DELETE FROM sessions');
  db.exec('DELETE FROM webhook_logs');
  db.exec('DELETE FROM webhooks');
  db.exec('DELETE FROM games');
  db.exec('DELETE FROM packs');
}

function seedGame(overrides = {}) {
  const defaults = {
    pack_name: 'Party Pack 7',
    title: 'Quiplash 3',
    min_players: 3,
    max_players: 8,
    length_minutes: 15,
    has_audience: 1,
    family_friendly: 1,
    game_type: 'Writing',
    enabled: 1,
    upvotes: 0,
    downvotes: 0,
    popularity_score: 0,
    ticker: null,
  };
  const g = { ...defaults, ...overrides };
  const result = db.prepare(`
    INSERT INTO games (pack_name, title, min_players, max_players, length_minutes, has_audience, family_friendly, game_type, enabled, upvotes, downvotes, popularity_score, ticker)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(g.pack_name, g.title, g.min_players, g.max_players, g.length_minutes, g.has_audience, g.family_friendly, g.game_type, g.enabled, g.upvotes, g.downvotes, g.popularity_score, g.ticker);
  return db.prepare('SELECT * FROM games WHERE id = ?').get(result.lastInsertRowid);
}

function seedSession(overrides = {}) {
  const defaults = { is_active: 1, notes: null };
  const s = { ...defaults, ...overrides };
  const result = db.prepare('INSERT INTO sessions (is_active, notes) VALUES (?, ?)').run(s.is_active, s.notes);
  return db.prepare('SELECT * FROM sessions WHERE id = ?').get(result.lastInsertRowid);
}

function seedSessionGame(sessionId, gameId, overrides = {}) {
  const defaults = { status: 'playing', played_at: new Date().toISOString() };
  const sg = { ...defaults, ...overrides };
  const result = db.prepare(`
    INSERT INTO session_games (session_id, game_id, status, played_at)
    VALUES (?, ?, ?, ?)
  `).run(sessionId, gameId, sg.status, sg.played_at);
  return db.prepare('SELECT * FROM session_games WHERE id = ?').get(result.lastInsertRowid);
}

function seedVote(sessionId, gameId, username, voteType, timestamp) {
  const vt = voteType === 'up' ? 1 : -1;
  const ts = timestamp || new Date().toISOString();
  db.prepare(`
    INSERT INTO live_votes (session_id, game_id, username, vote_type, timestamp)
    VALUES (?, ?, ?, ?, ?)
  `).run(sessionId, gameId, username, vt, ts);
}

module.exports = {
  getAuthToken,
  getAuthHeader,
  cleanDb,
  seedGame,
  seedSession,
  seedSessionGame,
  seedVote,
  db,
};
