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

const router = Router();

// Get all materials
router.get('/', async (req, res) => {
    try {
        const [rows] = await pool.query(`
            SELECT m.*, v.name as vendor_name 
            FROM materials m
            LEFT JOIN vendors v ON m.vendor_id = v.id
            ORDER BY m.name
        `);
        res.json(rows);
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

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

// Create material
router.post('/', async (req, res) => {
    const { vendor_id, name, description, unit_price, category } = req.body;
    const id = uuidv4();
    try {
        await pool.query(
            'INSERT INTO materials (id, vendor_id, name, description, unit_price) VALUES (?, ?, ?, ?, ?)',
            [id, vendor_id, name, description, unit_price || 0]
        );
        res.status(201).json({ id, vendor_id, name, description, unit_price });
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

// Update material
router.put('/:id', async (req, res) => {
    const { vendor_id, name, description, unit_price, category } = req.body;
    try {
        await pool.query(
            'UPDATE materials SET vendor_id = ?, name = ?, description = ?, unit_price = ? WHERE id = ?',
            [vendor_id, name, description, unit_price, req.params.id]
        );
        res.json({ id: req.params.id, vendor_id, name, description, unit_price });
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

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