import { Router, type Request } from "express";
import { requireAuth, requireEmployee } from "../auth/middleware";
import { confirmClosure, getClosureSummary, getOrCreateClosure } from "../services/closure";

export const closureRouter = Router();
closureRouter.use(requireAuth, requireEmployee);

function periodParam(req: Request): string {
  const period = req.query.period;
  if (typeof period === "string" && /^\d{4}-\d{2}$/.test(period)) return period;
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
}

closureRouter.get("/", (req, res) => {
  const employeeId = req.user!.employeeId!;
  const period = periodParam(req);
  res.json({
    closure: getOrCreateClosure(employeeId, period),
    summary: getClosureSummary(employeeId, period),
  });
});

closureRouter.post("/confirm", (req, res) => {
  const employeeId = req.user!.employeeId!;
  const period = req.body?.period;
  if (typeof period !== "string" || !/^\d{4}-\d{2}$/.test(period)) {
    res.status(400).json({ error: "Neplatné období." });
    return;
  }
  try {
    confirmClosure(employeeId, period);
    res.json({ ok: true });
  } catch (err) {
    res.status(400).json({ error: err instanceof Error ? err.message : "Potvrzení se nezdařilo" });
  }
});
