import { Router } from "express";
import { db } from "@workspace/db";
import { accountsTable, transactionsTable } from "@workspace/db";
import { eq, and, gte, lte, sql } from "drizzle-orm";

const router = Router();

router.get("/", async (req, res) => {
  const accounts = await db.select().from(accountsTable).orderBy(accountsTable.name);
  res.json(accounts.map((a) => ({
    id: a.id,
    name: a.name,
    type: a.type,
    balance: Number(a.balance),
    notes: a.notes,
    createdAt: a.createdAt.toISOString(),
  })));
});

router.post("/", async (req, res) => {
  const { name, type, balance, notes } = req.body;
  if (!name || !type) return res.status(400).json({ error: "name and type required" });
  const [a] = await db
    .insert(accountsTable)
    .values({ name, type, balance: String(balance ?? 0), notes })
    .returning();
  res.status(201).json({ id: a.id, name: a.name, type: a.type, balance: Number(a.balance), notes: a.notes, createdAt: a.createdAt.toISOString() });
});

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

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

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

export default router;
