const express = require('express');
const router = express.Router();
const mongoose = require("mongoose")
const ServiceRecord = require("../models/ServiceRecord")

router.post('/add', async (req, res) => {
    const { serviceRecordCode, date, car, servicename } = req.body;
    if (!serviceRecordCode || !date || !car || !servicename) {
        return res.status(400).json({ message: "All fields are required" });
    }
    if (!mongoose.Types.ObjectId.isValid(car) || !mongoose.Types.ObjectId.isValid(servicename)) {
        return res.status(400).json({ message: "Invalid Car or Service selection" });
    }
    try {
        const record = new ServiceRecord({ serviceRecordCode, date, car, servicename });
        await record.save();
        res.status(201).json(record); 
    } catch (error) {
        if (error.code === 11000) {
            return res.status(400).json({ message: "Record Code already exists" });
        }
        res.status(400).json({ message: error.message });
    }
});

router.get('/all', async (req, res) => {
    try {
        const records = await ServiceRecord.find().populate('car').populate('servicename');
        res.json(records); 
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});
router.put('/update/:id', async (req, res) => {
    const {id}= req.params;
    const {serviceRecordCode , date, car , servicename} = req.body;
    try {
        const update = await ServiceRecord.findByIdAndUpdate(id,{serviceRecordCode , date , car, servicename}, {new:true});
        res.status(200).json(update);
    } catch (error) {
         res.status(500).json({ message: error.message });
    }
})

router.delete('/delete/:id', async (req, res) => {
    const {id} = req.params;
    try {
        const deleted = await ServiceRecord.findByIdAndDelete(id);
        res.status(200).json(deleted);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
})
module.exports = router;