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

const serviceSchema = new mongoose.Schema({
    serviceCode: { type: String, required: true, unique: true },
    servicename: { type: String, required: true },
    price: { type: String, required: true }
})

const Service = mongoose.model("Service", serviceSchema)

router.post('/add', async (req, res)=>{
    const {serviceCode, servicename, price} = req.body;
    try{
    const service = new Service({ serviceCode, servicename, price });
    await service.save();
    res.status(201).json(service);
    }
    catch{
        res.status(400).json({ message: error.message });
    }
});

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

router.put('/update/:id', async (req, res)=>{
    try {
        const { id } = req.params;
        const { serviceCode, servicename, price } = req.body;
        const service = await Service.findByIdAndUpdate(id, { serviceCode, servicename, price }, { new: true });
        res.status(200).json(service);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

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