import { Router } from 'express';
import { prisma } from '../db.js';
import { requireAuth } from '../middleware.js';
import {
  checkAchievements,
  getUnlockedAchievements,
  listAchievementsForUser,
} from '../achievements.js';

const router = Router();

/** Full list for the logged-in player (locked + unlocked). */
router.get('/', requireAuth, async (req, res) => {
  try {
    await checkAchievements(req.session.userId);
    const achievements = await listAchievementsForUser(req.session.userId);
    const unlocked = achievements.filter((a) => a.unlockedAt).length;
    res.json({
      achievements,
      unlocked,
      total: achievements.length,
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Failed to load achievements' });
  }
});

/** Public unlocked badges for a username. */
router.get('/player/:username', async (req, res) => {
  try {
    const username = String(req.params.username || '').trim();
    const user = await prisma.user.findFirst({
      where: { username, role: 'user' },
      select: { id: true },
    });
    if (!user) return res.status(404).json({ error: 'Player not found' });

    await checkAchievements(user.id);
    const achievements = await getUnlockedAchievements(user.id);
    res.json({ achievements });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Failed to load achievements' });
  }
});

export default router;
