const express = require('express');
const router = express.Router();
const database = require('../config/database');
const { optionalAuth } = require('../middleware/auth');
const { v4: uuidv4 } = require('uuid');

router.post('/', optionalAuth, async (req, res) => {
    try {
        const { pickup_location, dropoff_location, distance_miles, vehicle_id, extras } = req.body;
        const quoteReference = 'QT' + Date.now().toString().slice(-8);
        
        const vehicle = await database.get('SELECT price_per_mile, minimum_fare FROM vehicles WHERE id = ?', [vehicle_id]);
        const baseFare = Math.max(vehicle.minimum_fare, distance_miles * vehicle.price_per_mile);
        
        let extrasTotal = 0;
        for (const extraId of extras || []) {
            const extra = await database.get('SELECT price FROM extras WHERE id = ?', [extraId]);
            if (extra) extrasTotal += extra.price;
        }
        
        const totalPrice = baseFare + extrasTotal;
        
        await database.run(
            `INSERT INTO quotes (quote_reference, user_id, pickup_location, dropoff_location, distance_miles, 
             vehicle_id, base_fare, extras_total, total_price, extras_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [quoteReference, req.user?.id || null, pickup_location, dropoff_location, distance_miles,
             vehicle_id, baseFare, extrasTotal, totalPrice, JSON.stringify(extras || [])]
        );
        
        res.status(201).json({ quote_reference: quoteReference, base_fare: baseFare, extras_total: extrasTotal, total_price: totalPrice });
    } catch (error) {
        res.status(500).json({ error: 'Failed to create quote' });
    }
});

module.exports = router;
