import { Router } from "express";
import { db } from "@workspace/db";
import { productsTable } from "@workspace/db";
import { eq } from "drizzle-orm";

const router = Router();

router.get("/", async (req, res) => {
  const products = await db.select().from(productsTable).orderBy(productsTable.name);
  res.json(products.map((p) => ({
    id: p.id,
    name: p.name,
    unit: p.unit,
    createdAt: p.createdAt.toISOString(),
  })));
});

router.post("/", async (req, res) => {
  const { name, unit } = req.body;
  if (!name || !unit) return res.status(400).json({ error: "name and unit required" });
  const [p] = await db.insert(productsTable).values({ name, unit }).returning();
  res.status(201).json({ id: p.id, name: p.name, unit: p.unit, createdAt: p.createdAt.toISOString() });
});

router.get("/:id", async (req, res) => {
  const id = parseInt(req.params.id);
  const [p] = await db.select().from(productsTable).where(eq(productsTable.id, id));
  if (!p) return res.status(404).json({ error: "Not found" });
  res.json({ id: p.id, name: p.name, unit: p.unit, createdAt: p.createdAt.toISOString() });
});

router.patch("/:id", async (req, res) => {
  const id = parseInt(req.params.id);
  const { name, unit } = req.body;
  const updates: Record<string, unknown> = {};
  if (name !== undefined) updates.name = name;
  if (unit !== undefined) updates.unit = unit;
  const [p] = await db.update(productsTable).set(updates).where(eq(productsTable.id, id)).returning();
  if (!p) return res.status(404).json({ error: "Not found" });
  res.json({ id: p.id, name: p.name, unit: p.unit, createdAt: p.createdAt.toISOString() });
});

router.delete("/:id", async (req, res) => {
  const id = parseInt(req.params.id);
  await db.delete(productsTable).where(eq(productsTable.id, id));
  res.status(204).end();
});

export default router;
