import { Router } from "express";
import { randomUUID } from "node:crypto";
import { readDb, writeDb } from "../storage/jsondb";
import { TimerRule } from "../types";
import { nowIso } from "../utils/time";
import { z } from "zod";

const router = Router();

const ruleSchema = z.object({
  tags: z.array(z.string().min(1)).min(1),
  seedLimitSeconds: z.number().int().min(60).max(60 * 60 * 24 * 365),
  deleteFiles: z.boolean().optional(),
});

router.get("/rules", async (_req, res) => {
  const db = await readDb();
  res.json(db.timerRules ?? []);
});

router.post("/rules", async (req, res) => {
  const parsed = ruleSchema.safeParse(req.body);
  if (!parsed.success) {
    return res.status(400).json({ error: parsed.error.flatten() });
  }
  const db = await readDb();
  const rule: TimerRule = {
    id: randomUUID(),
    tags: parsed.data.tags,
    seedLimitSeconds: parsed.data.seedLimitSeconds,
    deleteFiles: parsed.data.deleteFiles ?? true,
    createdAt: nowIso(),
  };
  db.timerRules = [...(db.timerRules ?? []), rule];
  await writeDb(db);
  res.json(rule);
});

router.delete("/rules/:ruleId", async (req, res) => {
  const db = await readDb();
  const next = (db.timerRules ?? []).filter((rule) => rule.id !== req.params.ruleId);
  if (next.length === (db.timerRules ?? []).length) {
    return res.status(404).json({ error: "Rule not found" });
  }
  db.timerRules = next;
  await writeDb(db);
  res.json({ ok: true });
});

router.get("/logs", async (_req, res) => {
  const db = await readDb();
  res.json(db.timerLogs ?? []);
});

router.get("/summary", async (_req, res) => {
  const db = await readDb();
  res.json(db.timerSummary ?? null);
});

export default router;
