const express = require('express');
const router = express.Router();
const database = require('../config/database');

// Get all active vehicles
router.get('/', async (req, res) => {
    try {
        const vehicles = await database.all(
            'SELECT * FROM vehicles WHERE is_active = 1 ORDER BY price_per_mile'
        );
        
        vehicles.forEach(v => {
            if (v.features) v.features = JSON.parse(v.features);
        });
        
        res.json({ vehicles });
    } catch (error) {
        console.error('Get vehicles error:', error);
        res.status(500).json({ error: 'Failed to fetch vehicles' });
    }
});

// Get single vehicle
router.get('/:id', async (req, res) => {
    try {
        const vehicle = await database.get(
            'SELECT * FROM vehicles WHERE id = ?',
            [req.params.id]
        );
        
        if (!vehicle) {
            return res.status(404).json({ error: 'Vehicle not found' });
        }
        
        if (vehicle.features) vehicle.features = JSON.parse(vehicle.features);
        
        res.json({ vehicle });
    } catch (error) {
        console.error('Get vehicle error:', error);
        res.status(500).json({ error: 'Failed to fetch vehicle' });
    }
});

module.exports = router;
