const router = require('express').Router()
const {MasterModel} = require('./model/master')
const mongoose = require("mongoose")
const {OrderModel} = require("./model/order")


router.get("/masters", async (req, res, next) => {
    try {
        const masters = await MasterModel.find({});
        const orders = await OrderModel.find({});

        const mastersWithOrders = masters.map((master) => {
            const masterOrders = orders.filter((order) => {
                return (
                    order?.master && order.master.toString() === master._id.toString()
                );
            });

            const schedule = masterOrders.map((order) => ({
                id: order._id,
                startWashTime: order.startWashTime,
                endWashTime: order.endWashTime,
            }));

            return {
                id: master._id,
                name: master.name,
                schedule: schedule,
                phone: master.phone,
            };
        });

        res.status(200).send({ success: true, body: mastersWithOrders });
    } catch (error) {
        next(error);
    }
});

router.delete('/masters/:id', async (req, res,next) => {
    const { id } = req.params;

    if (!mongoose.Types.ObjectId.isValid(id)){
        throw new Error('ID is required')
    }

    try {
        const master = await MasterModel.findByIdAndDelete(id, {
            new: true,
        });
        if (!master) {
            throw new Error('master not found')
        }
        res.status(200).send({success: true, body: master})
    } catch (error) {
        next(error)
    }
})


router.post('/masters',  async (req, res,next) => {

    const {name, phone} =  req.body

    if (!name || !phone ){
        throw new Error('Enter name and phone')
    }
    try {
        const master =  await MasterModel.create({name, phone})
        res.status(200).send({success: true, body: master})
    } catch (error) {
        next(error)
    }
})


router.patch('/masters/:id', async (req, res, next) => {
    const { id } = req.params;

    if (!mongoose.Types.ObjectId.isValid(id)) {
        throw new Error('ID is required')
    }

    const { name, phone } = req.body;

    if (!name && !phone) {
        throw new Error('Enter name and phone')
    }


    try {
        const updateData = {};
        if (name) updateData.name = name;
        if (phone) updateData.phone = phone;

        const master = await MasterModel.findByIdAndUpdate(
            id,
            updateData,
            { new: true }
        );

        if (!master) {
            throw new Error('master not found')
        }

        res.status(200).send({ success: true, body: master });
    } catch (error) {
        next(error);
    }
});

module.exports = router
