'use strict';
const db = require('../../db/db');
const { stmts } = require('./_shared');
const { awardXP, awardCoins } = require('./service');

/* ═══════════════════════════════════════════════════════════════════════
   Gamification — admin handlers
   Mounted under /api/gamification/admin/*
   ═══════════════════════════════════════════════════════════════════════ */

const ADMIN_AWARD_MAX = 1_000_000;

/* POST /api/gamification/admin/award — award XP or coins to user */
function adminAward(req, res) {
  const { userId, xp, coins, reason } = req.body;
  if (!userId) return res.status(400).json({ error: 'userId required' });
  const xpNum    = Number(xp)    || 0;
  const coinsNum = Number(coins) || 0;
  if (xpNum    < 0 || xpNum    > ADMIN_AWARD_MAX) return res.status(400).json({ error: `xp must be 0..${ADMIN_AWARD_MAX}` });
  if (coinsNum < 0 || coinsNum > ADMIN_AWARD_MAX) return res.status(400).json({ error: `coins must be 0..${ADMIN_AWARD_MAX}` });
  const user = stmts.checkUserById.get(userId);
  if (!user) return res.status(404).json({ error: 'User not found' });
  if (xpNum    > 0) awardXP(userId, xpNum, reason || 'Admin award');
  if (coinsNum > 0) awardCoins(userId, coinsNum, reason || 'Admin award');
  const updated = stmts.getUserGamInfo.get(userId);
  res.json({ ok: true, ...updated });
}

/* POST /api/gamification/admin/reset — reset user gamification */
const _resetTx = db.transaction((userId) => {
  stmts.adminResetUser.run(userId);
  stmts.deleteXpLog.run(userId);
  stmts.deleteUserAchs.run(userId);
  stmts.deleteDailyGoals.run(userId);
  stmts.deleteChallenges.run(userId);
  stmts.deleteUserPurch.run(userId);
});

function adminReset(req, res) {
  const { userId } = req.body;
  if (!userId) return res.status(400).json({ error: 'userId required' });
  _resetTx(userId);
  res.json({ ok: true });
}

/* GET /api/gamification/admin/stats — global gamification stats */
function adminGamStats(_req, res) {
  const totalXP         = stmts.adminTotalXP.get().v;
  const totalCoins      = stmts.adminTotalCoins.get().v;
  const avgLevel        = stmts.adminAvgLevel.get().v;
  const achievementCount = stmts.adminAchCount.get().v;
  const topByXP         = stmts.adminTopXP.all();
  const recentXP        = stmts.adminRecentXP.all();
  const totalPurchases  = stmts.adminTotalPurch.get().v;
  const recentPurchases = stmts.adminRecentPurch.all();
  res.json({ totalXP, totalCoins, avgLevel, achievementCount, totalPurchases, topByXP, recentXP, recentPurchases });
}

/* GET /api/gamification/admin/user/:id — user gamification details */
function adminGetUser(req, res) {
  const uid = Number(req.params.id);
  const user = stmts.adminGetUserFull.get(uid);
  if (!user) return res.status(404).json({ error: 'User not found' });
  const achievements = stmts.adminGetUserAchs.all(uid);
  const purchases    = stmts.adminGetUserPurch.all(uid);
  const xpHistory    = stmts.adminGetUserXPH.all(uid);
  res.json({ user, achievements, purchases, xpHistory });
}

module.exports = { adminAward, adminReset, adminGamStats, adminGetUser };
