import { Router } from "express";
import type { ParamsDictionary } from "express-serve-static-core";
import type { RowDataPacket } from "mysql2";
import db from "../db.js";
import { parseJson } from "../utils/parseJson.js";

type CampaignParams = ParamsDictionary & { campaignId: string };

const router = Router({ mergeParams: true });

// GET /api/campaigns/:campaignId/rolls
router.get<CampaignParams>("/", async (req, res) => {
  try {
    const { campaignId } = req.params;
    const [rows] = await db.execute<RowDataPacket[]>(
      "SELECT * FROM roll_log WHERE campaign_id = ? ORDER BY created_at DESC LIMIT 50",
      [campaignId]
    );
    const parsed = rows.map((r) => ({
      ...r,
      rolls: (parseJson(r.rolls) as unknown) as unknown[],
      advantage: r.advantage === 1,
      disadvantage: r.disadvantage === 1,
      nat20: r.nat20 === 1,
    }));
    res.json(parsed);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: "Internal server error" });
  }
});

export default router;
