import { Router } from 'express';
import pool from '../db.js';
import { v4 as uuidv4 } from 'uuid';
const router = Router();
// Get all invoices
router.get('/', async (req, res) => {
    try {
        const [rows] = await pool.query(`
      SELECT 
        i.*, 
        c.name as customer_name,
        c.address as customer_address,
        c.email as customer_email,
        c.phone as customer_phone,
        c.vat_number as customer_vat_no,
        c.company as customer_company,
        p.name as project_name 
      FROM invoices i 
      LEFT JOIN customers c ON i.customer_id = c.id 
      LEFT JOIN projects p ON i.project_id = p.id 
      ORDER BY i.date DESC
    `);
        res.json(rows);
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});
// Create invoice
router.post('/', async (req, res) => {
    const { customer_id, project_id, quotation_id, invoice_number, date, due_date, total_amount, vat_amount, grand_total, status, notes, items } = req.body;
    const id = uuidv4();
    try {
        await pool.query('INSERT INTO invoices (id, customer_id, project_id, quotation_id, invoice_number, date, due_date, total_amount, vat_amount, grand_total, status, notes, items) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [id, customer_id, project_id, quotation_id, invoice_number, date, due_date, total_amount, vat_amount, grand_total, status || 'Draft', notes, JSON.stringify(items)]);
        res.status(201).json({ id, customer_id, project_id, quotation_id, invoice_number, date, due_date, total_amount, vat_amount, grand_total, status, notes, items });
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});
// Delete invoice
router.delete('/:id', async (req, res) => {
    const { id } = req.params;
    try {
        await pool.query('DELETE FROM invoices WHERE id = ?', [id]);
        res.json({ message: 'Invoice deleted successfully' });
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});
export default router;
//# sourceMappingURL=invoices.js.map