const { db } = require("./db");

function touchUserStats(userId) {
  const now = Date.now();
  db.prepare(
    "INSERT INTO stats (user_id, messages, commands, updated_at) VALUES (?, 0, 0, ?) " +
      "ON CONFLICT(user_id) DO UPDATE SET updated_at = excluded.updated_at"
  ).run(userId, now);
}

function incrementMessages(userId) {
  const now = Date.now();
  db.prepare(
    "INSERT INTO stats (user_id, messages, commands, updated_at) VALUES (?, 1, 0, ?) " +
      "ON CONFLICT(user_id) DO UPDATE SET messages = messages + 1, updated_at = excluded.updated_at"
  ).run(userId, now);
}

function incrementCommands(userId) {
  const now = Date.now();
  db.prepare(
    "INSERT INTO stats (user_id, messages, commands, updated_at) VALUES (?, 0, 1, ?) " +
      "ON CONFLICT(user_id) DO UPDATE SET commands = commands + 1, updated_at = excluded.updated_at"
  ).run(userId, now);
}

function getLeaderboard(limit = 20) {
  return db
    .prepare(
      "SELECT user_profiles.internal_username AS username, " +
        "COALESCE(discord.avatar, twitch.avatar, youtube.avatar) AS avatar, " +
        "stats.messages, stats.commands " +
        "FROM stats " +
        "JOIN user_profiles ON user_profiles.id = stats.user_id " +
        "LEFT JOIN user_identities AS discord ON discord.user_id = user_profiles.id AND discord.provider = 'discord' " +
        "LEFT JOIN user_identities AS twitch ON twitch.user_id = user_profiles.id AND twitch.provider = 'twitch' " +
        "LEFT JOIN user_identities AS youtube ON youtube.user_id = user_profiles.id AND youtube.provider = 'youtube' " +
        "ORDER BY stats.messages DESC LIMIT ?"
    )
    .all(limit);
}

module.exports = {
  touchUserStats,
  incrementMessages,
  incrementCommands,
  getLeaderboard
};
