import { Router } from "express";
import { randomUUID } from "node:crypto";
import { readDb, writeDb } from "../storage/jsondb"
import { profileSchema } from "../utils/validators"
import { nowIso } from "../utils/time"

const router = Router();

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

router.post("/", async (req, res) => {
  const parsed = profileSchema.safeParse(req.body);
  if (!parsed.success) {
    return res.status(400).json({ error: parsed.error.flatten() });
  }
  const db = await readDb();
  const profile = {
    id: randomUUID(),
    createdAt: nowIso(),
    ...parsed.data,
  };
  db.profiles.push(profile);
  await writeDb(db);
  res.json(profile);
});

router.put("/:profileId", async (req, res) => {
  const parsed = profileSchema.safeParse(req.body);
  if (!parsed.success) {
    return res.status(400).json({ error: parsed.error.flatten() });
  }
  const db = await readDb();
  const index = db.profiles.findIndex((p) => p.id === req.params.profileId);
  if (index === -1) {
    return res.status(404).json({ error: "Profile not found" });
  }
  db.profiles[index] = {
    ...db.profiles[index],
    ...parsed.data,
  };
  await writeDb(db);
  res.json(db.profiles[index]);
});

router.delete("/:profileId", async (req, res) => {
  const db = await readDb();
  const next = db.profiles.filter((p) => p.id !== req.params.profileId);
  if (next.length === db.profiles.length) {
    return res.status(404).json({ error: "Profile not found" });
  }
  db.profiles = next;
  await writeDb(db);
  res.json({ ok: true });
});

router.post("/apply", async (req, res) => {
  const { profileId, hash } = req.body ?? {};
  const db = await readDb();
  const profile = db.profiles.find((p) => p.id === profileId);
  if (!profile) {
    return res.status(404).json({ error: "Profile not found" });
  }
  res.json({
    hash,
    allowIp: profile.allowIp,
    delayMs: profile.delayMs,
    targetLoops: profile.targetLoops,
  });
});

export default router;
