import { Router } from "express";
import type { RowDataPacket } from "mysql2";
import db from "../db.js";
import { requireAuth } from "../auth/middleware.js";

const router = Router();

// GET /api/spells — all spells, optionally filtered by class
router.get("/", requireAuth, async (req, res, next) => {
  try {
    const { class: spellClass } = req.query;
    let sql = "SELECT * FROM spells ORDER BY class, tier, name";
    const params: string[] = [];
    if (spellClass && typeof spellClass === "string") {
      sql = "SELECT * FROM spells WHERE class = ? OR class = 'both' ORDER BY tier, name";
      params.push(spellClass);
    }
    const [rows] = await db.execute<RowDataPacket[]>(sql, params);
    res.json(rows);
  } catch (err) {
    next(err);
  }
});

export default router;
