"use strict";
const { Router } = require("express");
const { query } = require("../db");
const router = Router();

function parseInvoice(r) {
  return {
    ...r,
    studentId: r.student_id,
    invoiceNumber: r.invoice_number,
    items: typeof r.items === "string" ? JSON.parse(r.items) : (r.items || []),
    amountPaid: r.amount_paid,
    issuedAt: r.issued_at ? new Date(r.issued_at).toISOString() : null,
    dueDate: r.due_date,
    studentName: r.student_name || "Unknown",
  };
}

router.get("/invoices", async (req, res) => {
  const { studentId } = req.query;
  let sql = "SELECT i.*, CONCAT(s.first_name, ' ', s.last_name) AS student_name FROM invoices i LEFT JOIN students s ON s.id = i.student_id";
  const params = [];
  if (studentId) { sql += " WHERE i.student_id = ?"; params.push(parseInt(studentId)); }
  sql += " ORDER BY i.issued_at DESC";
  const rows = await query(sql, params);
  res.json(rows.map(parseInvoice));
});

router.post("/invoices", async (req, res) => {
  const { studentId, term, items, dueDate, notes } = req.body || {};
  if (!studentId || !term || !Array.isArray(items)) return res.status(400).json({ error: "studentId, term, items required" });
  const total = items.reduce((a, b) => a + (b.amount || 0), 0);
  const invoiceNumber = `INV-${Date.now()}`;
  await query("INSERT INTO invoices (invoice_number, student_id, term, items, total, amount_paid, status, due_date, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
    [invoiceNumber, studentId, term, JSON.stringify(items), total, 0, "pending", dueDate || null, notes || null]);
  const [row] = await query("SELECT i.*, CONCAT(s.first_name, ' ', s.last_name) AS student_name FROM invoices i LEFT JOIN students s ON s.id = i.student_id WHERE i.id = LAST_INSERT_ID()");
  res.status(201).json(parseInvoice(row));
});

router.patch("/invoices/:id", async (req, res) => {
  const id = parseInt(req.params.id);
  if (!id) return res.status(400).json({ error: "Invalid id" });
  const [existing] = await query("SELECT * FROM invoices WHERE id = ?", [id]);
  if (!existing) return res.status(404).json({ error: "Not found" });
  const { items, amountPaid, status, dueDate, notes } = req.body || {};
  const finalItems = items || (typeof existing.items === "string" ? JSON.parse(existing.items) : existing.items);
  const total = finalItems.reduce((a, b) => a + (b.amount || 0), 0);
  const paid = amountPaid !== undefined ? amountPaid : existing.amount_paid;
  let finalStatus = status || (paid >= total ? "paid" : paid > 0 ? "partial" : "pending");
  await query("UPDATE invoices SET items = ?, total = ?, amount_paid = ?, status = ?, due_date = ?, notes = ? WHERE id = ?",
    [JSON.stringify(finalItems), total, paid, finalStatus, dueDate !== undefined ? dueDate : existing.due_date, notes !== undefined ? notes : existing.notes, id]);
  const [row] = await query("SELECT i.*, CONCAT(s.first_name, ' ', s.last_name) AS student_name FROM invoices i LEFT JOIN students s ON s.id = i.student_id WHERE i.id = ?", [id]);
  res.json(parseInvoice(row));
});

router.delete("/invoices/:id", async (req, res) => {
  const id = parseInt(req.params.id);
  if (!id) return res.status(400).json({ error: "Invalid id" });
  await query("DELETE FROM invoices WHERE id = ?", [id]);
  res.status(204).end();
});

module.exports = router;
