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

const router = Router();

// Get all projects
router.get('/', async (req, res) => {
    try {
        const [rows] = await pool.query(`
      SELECT p.*, c.name as customer_name 
      FROM projects p 
      LEFT JOIN customers c ON p.customer_id = c.id 
      ORDER BY p.created_at DESC
    `);
        res.json(rows);
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

// Get project by ID
router.get('/:id', async (req, res) => {
    try {
        const [rows]: any = await pool.query(`
      SELECT p.*, c.name as customer_name 
      FROM projects p 
      LEFT JOIN customers c ON p.customer_id = c.id 
      WHERE p.id = ?
    `, [req.params.id]);
        if (rows.length === 0) {
            return res.status(404).json({ error: 'Project not found' });
        }
        res.json(rows[0]);
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

// Create project
router.post('/', async (req, res) => {
    const { name, customer_id, description, status, start_date, end_date, budget } = req.body;
    const id = uuidv4();
    try {
        // Generate project number
        const [countRows]: any = await pool.query('SELECT COUNT(*) as count FROM projects');
        const nextNum = (countRows[0].count + 1).toString().padStart(3, '0');
        const project_number = `PR${nextNum}`;

        await pool.query(
            'INSERT INTO projects (id, project_number, name, customer_id, description, status, start_date, end_date, budget) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
            [id, project_number, name, customer_id, description, status, start_date, end_date, budget]
        );
        res.status(201).json({ id, project_number, name, customer_id, description, status, start_date, end_date, budget });
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

// Update project
router.put('/:id', async (req, res) => {
    const { name, customer_id, description, status, start_date, end_date, budget, profit_margin } = req.body;
    try {
        await pool.query(
            'UPDATE projects SET name = ?, customer_id = ?, description = ?, status = ?, start_date = ?, end_date = ?, budget = ?, profit_margin = ? WHERE id = ?',
            [name, customer_id, description, status, start_date, end_date, budget, profit_margin, req.params.id]
        );
        res.json({ id: req.params.id, name, customer_id, description, status, start_date, end_date, budget, profit_margin });
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

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