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

const carSchema = new mongoose.Schema({
    plateNumber: { type: String, required: true, unique: true },
    type:{type: String, required:true},
    model : {type: String, required:true},
    manufacturedDate: {type: Date, required:true},
    drivernumber: {type: Number, required:true},
    mechanicname: {type: String, required:true}
})

const Car = mongoose.model("Car", carSchema)


router.post('/add', async (req, res) => {
    const {plateNumber, type , model , manufacturedDate , drivernumber , mechanicname}= req.body;
      try{
    const car = new Car({ plateNumber, type , model , manufacturedDate , drivernumber , mechanicname });
    await car.save();
    res.status(201).json(car);
      } catch (error) {
        res.status(400).json({ message: error.message });
      }
});


router.get('/all', async (req, res) => {
    try {
        const cars = await Car.find();
        res.status(200).json(cars);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});


router.put('/update/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const { plateNumber, type, model, manufacturedDate, drivernumber, mechanicname } = req.body;
        const car = await Car.findByIdAndUpdate(id, { plateNumber, type, model, manufacturedDate, drivernumber, mechanicname }, { new: true });
        res.status(200).json(car);
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
});

router.delete('/delete/:id', async (req, res)=>{
    const {id} = req.params;
    const del = await Car.findByIdAndDelete(id);
    res.status(200).json(del);
})


module.exports = router;