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

function getProfileStats({ userId }) {
  if (!userId) {
    return { stats: [] };
  }
  const row = db
    .prepare("SELECT created_count FROM auto_vc_stats WHERE user_id = ?")
    .get(userId);
  if (!row) {
    return { stats: [] };
  }
  return {
    stats: [
      {
        label: "Rooms created",
        value: row.created_count
      }
    ]
  };
}

function getLeaderboards({ limit = 10 }) {
  const rows = db
    .prepare(
      "SELECT auto_vc_stats.user_id AS user_id, " +
        "auto_vc_stats.created_count AS total, " +
        "user_profiles.internal_username AS username " +
        "FROM auto_vc_stats " +
        "LEFT JOIN user_profiles ON user_profiles.id = auto_vc_stats.user_id " +
        "ORDER BY auto_vc_stats.created_count DESC LIMIT ?"
    )
    .all(limit);

  return {
    boards: [
      {
        id: "rooms-created",
        title: "Most rooms created",
        valueLabel: "Rooms",
        rows: rows.map((row) => ({
          username: row.username || row.user_id,
          value: row.total
        }))
      }
    ]
  };
}

module.exports = {
  getProfileStats,
  getLeaderboards
};
