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

const router = Router();

const fmt = (r: typeof invoicesTable.$inferSelect) => ({
  ...r,
  subtotal: Number(r.subtotal),
  discount: Number(r.discount),
  tax: Number(r.tax),
  total: Number(r.total),
  createdAt: r.createdAt.toISOString(),
});

router.get("/", async (req, res) => {
  const { partyType, partyId } = req.query;
  let query = db.select().from(invoicesTable);
  const rows = await query.orderBy(desc(invoicesTable.createdAt));
  let filtered = rows;
  if (partyType) filtered = filtered.filter(r => r.partyType === partyType);
  if (partyId) filtered = filtered.filter(r => r.partyId === parseInt(partyId as string));
  res.json(filtered.map(fmt));
});

router.post("/", async (req, res) => {
  const { invoiceNumber, partyType, partyId, partyName, date, items, subtotal, discount, tax, total, notes } = req.body;
  if (!date) return res.status(400).json({ error: "date required" });
  const [r] = await db.insert(invoicesTable).values({
    invoiceNumber: invoiceNumber || `INV-${Date.now()}`,
    partyType, partyId, partyName, date,
    items: items || [],
    subtotal: subtotal || 0,
    discount: discount || 0,
    tax: tax || 0,
    total: total || 0,
    notes,
    paymentStatus: "pending",
  }).returning();
  res.status(201).json(fmt(r));
});

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

router.patch("/:id", async (req, res) => {
  const id = parseInt(req.params.id);
  const { paymentStatus, notes, discount, tax } = req.body;
  const updates: Record<string, unknown> = {};
  if (paymentStatus !== undefined) updates.paymentStatus = paymentStatus;
  if (notes !== undefined) updates.notes = notes;
  if (discount !== undefined) updates.discount = discount;
  if (tax !== undefined) updates.tax = tax;
  const [r] = await db.update(invoicesTable).set(updates).where(eq(invoicesTable.id, id)).returning();
  if (!r) return res.status(404).json({ error: "Not found" });
  res.json(fmt(r));
});

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

export default router;
