import { Router } from "express";
import { z } from "zod";
import { requireAuth, requireEmployee } from "../auth/middleware";
import {
  InvalidTransitionError,
  eventsInRange,
  getLiveStatus,
  recordEvent,
  summarize,
} from "../services/attendance";
import { parseRange } from "../util/dateRange";

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

const eventSchema = z.object({
  type: z.enum(["clock_in", "clock_out", "break_start", "break_end"]),
});

attendanceRouter.post("/event", (req, res) => {
  const parsed = eventSchema.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: "Invalid event type" });
    return;
  }

  const employeeId = req.user!.employeeId!;
  try {
    const event = recordEvent(employeeId, parsed.data.type);
    res.status(201).json({ event, status: getLiveStatus(employeeId) });
  } catch (err) {
    if (err instanceof InvalidTransitionError) {
      res.status(409).json({ error: err.message, status: err.current });
      return;
    }
    throw err;
  }
});

attendanceRouter.get("/state", (req, res) => {
  const employeeId = req.user!.employeeId!;
  res.json({ status: getLiveStatus(employeeId) });
});

attendanceRouter.get("/me", (req, res) => {
  const employeeId = req.user!.employeeId!;
  const { fromIso, toIso } = parseRange(req.query as Record<string, unknown>);
  const events = eventsInRange(employeeId, fromIso, toIso);
  const stats = summarize(events, new Date());
  res.json({ range: { from: fromIso, to: toIso }, ...stats });
});
