import { Router } from "express";
import { createNote, deleteNote, getNote, listNotes, manualSync, updateNote } from "./notes.service.js";
import type { CleanupQueue } from "../queue/queue.js";

export function notesRoutes(queue: CleanupQueue): Router {
  const router = Router();

  router.get("/notes", async (_req, res) => {
    const notes = await listNotes();
    res.json(notes);
  });

  router.get("/notes/:id", async (req, res) => {
    const note = await getNote(req.params.id);
    if (!note) {
      res.status(404).json({ error: "Not bulunamadi" });
      return;
    }
    res.json(note);
  });

  router.post("/notes", async (req, res) => {
    const { title, content } = req.body as { title?: string; content?: string };
    if (!title) {
      res.status(400).json({ error: "Baslik gerekli" });
      return;
    }
    const note = await createNote(title, content ?? "", queue);
    res.status(201).json(note);
  });

  router.put("/notes/:id", async (req, res) => {
    const { title, content } = req.body as { title?: string; content?: string };
    if (!title) {
      res.status(400).json({ error: "Baslik gerekli" });
      return;
    }
    const note = await updateNote(req.params.id, title, content ?? "", queue);
    if (!note) {
      res.status(404).json({ error: "Not bulunamadi" });
      return;
    }
    res.json(note);
  });

  router.delete("/notes/:id", async (req, res) => {
    const ok = await deleteNote(req.params.id, queue);
    if (!ok) {
      res.status(404).json({ error: "Not bulunamadi" });
      return;
    }
    res.status(204).send();
  });

  router.post("/notes/:id/sync", async (req, res) => {
    const ok = await manualSync(req.params.id, queue);
    if (!ok) {
      res.status(404).json({ error: "Not bulunamadi" });
      return;
    }
    res.status(202).json({ status: "syncing" });
  });

  return router;
}
