import { Router, type Request } from "express";
import { requireAuth, requireEmployee } from "../auth/middleware";
import { cancelMySignup, getAvailableSlotsForEmployee, getMySlotsForEmployee, signupForSlot } from "../services/shiftPlanning";

export const shiftsRouter = Router();
shiftsRouter.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")}`;
}

shiftsRouter.get("/available", (req, res) => {
  const employeeId = req.user!.employeeId!;
  res.json({ slots: getAvailableSlotsForEmployee(employeeId, periodParam(req)) });
});

shiftsRouter.get("/mine", (req, res) => {
  const employeeId = req.user!.employeeId!;
  res.json({ slots: getMySlotsForEmployee(employeeId, periodParam(req)) });
});

shiftsRouter.post("/:slotId/signup", (req, res) => {
  const slotId = Number(req.params.slotId);
  if (!Number.isInteger(slotId)) {
    res.status(400).json({ error: "Invalid slot id" });
    return;
  }
  try {
    signupForSlot(req.user!.employeeId!, slotId);
    res.status(201).json({ ok: true });
  } catch (err) {
    res.status(400).json({ error: err instanceof Error ? err.message : "Přihlášení se nezdařilo" });
  }
});

shiftsRouter.delete("/:slotId/signup", (req, res) => {
  const slotId = Number(req.params.slotId);
  if (!Number.isInteger(slotId)) {
    res.status(400).json({ error: "Invalid slot id" });
    return;
  }
  try {
    cancelMySignup(req.user!.employeeId!, slotId, req.user!.email);
    res.status(204).end();
  } catch (err) {
    res.status(400).json({ error: err instanceof Error ? err.message : "Zrušení se nezdařilo" });
  }
});
