import { Router } from 'express';
import pool from '../db.js';
import { v4 as uuidv4 } from 'uuid';

const router = Router();

// Get all customers
router.get('/', async (req, res) => {
    try {
        const [rows] = await pool.query('SELECT * FROM customers ORDER BY name');
        res.json(rows);
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

// Get customer by ID
router.get('/:id', async (req, res) => {
    try {
        const [rows]: any = await pool.query('SELECT * FROM customers WHERE id = ?', [req.params.id]);
        if (rows.length === 0) {
            return res.status(404).json({ error: 'Customer not found' });
        }
        res.json(rows[0]);
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

// Create customer
router.post('/', async (req, res) => {
    const { name, company, email, phone, address, vat_number } = req.body;
    const id = uuidv4();
    try {
        await pool.query(
            'INSERT INTO customers (id, name, company, email, phone, address, vat_number) VALUES (?, ?, ?, ?, ?, ?, ?)',
            [id, name, company, email, phone, address, vat_number]
        );
        res.status(201).json({ id, name, company, email, phone, address, vat_number });
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

// Update customer
router.put('/:id', async (req, res) => {
    const { name, company, email, phone, address, vat_number, balance } = req.body;
    try {
        await pool.query(
            'UPDATE customers SET name = ?, company = ?, email = ?, phone = ?, address = ?, vat_number = ?, balance = ? WHERE id = ?',
            [name, company, email, phone, address, vat_number, balance, req.params.id]
        );
        res.json({ id: req.params.id, name, company, email, phone, address, vat_number, balance });
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

// Delete customer
router.delete('/:id', async (req, res) => {
    try {
        await pool.query('DELETE FROM customers WHERE id = ?', [req.params.id]);
        res.status(204).send();
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

export default router;
