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

const router = Router();

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

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

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

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

// Delete vendor
router.delete('/:id', async (req, res) => {
    try {
        await pool.query('DELETE FROM vendors 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;
