import { Router } from "express";
import db from "../db.js";

const router = Router();

// GET /api/campaigns — list all campaigns
router.get("/", (_req, res) => {
  const campaigns = db
    .prepare("SELECT * FROM campaigns ORDER BY created_at DESC")
    .all();
  res.json(campaigns);
});

// POST /api/campaigns — create a campaign
router.post("/", (req, res) => {
  const { name } = req.body;
  if (!name || !name.trim()) {
    res.status(400).json({ error: "Campaign name is required" });
    return;
  }
  const result = db
    .prepare("INSERT INTO campaigns (name) VALUES (?)")
    .run(name.trim());
  const campaign = db
    .prepare("SELECT * FROM campaigns WHERE id = ?")
    .get(result.lastInsertRowid);
  res.status(201).json(campaign);
});

// GET /api/campaigns/:id — get a single campaign
router.get("/:id", (req, res) => {
  const campaign = db
    .prepare("SELECT * FROM campaigns WHERE id = ?")
    .get(req.params.id);
  if (!campaign) {
    res.status(404).json({ error: "Campaign not found" });
    return;
  }
  res.json(campaign);
});

// DELETE /api/campaigns/:id — delete a campaign (cascades to characters)
router.delete("/:id", (req, res) => {
  const result = db
    .prepare("DELETE FROM campaigns WHERE id = ?")
    .run(req.params.id);
  if (result.changes === 0) {
    res.status(404).json({ error: "Campaign not found" });
    return;
  }
  res.status(204).end();
});

export default router;
