import AppError from "../../errors/AppError";
import { createSchedulingNotifyCache } from "../../helpers/SchedulingNotifyCache";
import SchedulingNotify from "../../models/SchedulingNotify";


interface Request {
    schedulingNotifyId?: string,
    ticketId: string,
    statusChatEndId: string | number,
    schedulingDate: string,
    schedulingTime: string,
    message: string
}


const CreateSchedulingNotifyService = async ({
    schedulingNotifyId = '',
    ticketId,
    statusChatEndId,
    schedulingDate,
    schedulingTime,
    message
}: Request): Promise<SchedulingNotify> => {

    try {

        let schedulingNotify = null;

    if (schedulingNotifyId) {

        schedulingNotify = await SchedulingNotify.findOne({ where: { id: schedulingNotifyId } });

        if (schedulingNotify) {

            try {

                await schedulingNotify.update({ statusChatEndId, schedulingDate, schedulingTime, message });

            } catch (err) {

                throw new AppError("ERR_NO_SCHEDULING_NOTIFY_FOUND", 404);

            }


            //await scheduleNotify.reload({attributes: ["id", "name"]});
        }

    }

    if (!schedulingNotify) {

        schedulingNotify = await SchedulingNotify.create(
            {
                ticketId,
                statusChatEndId,
                schedulingDate,
                schedulingTime,
                message

            })
    }

    await createSchedulingNotifyCache(JSON.parse(JSON.stringify(schedulingNotify)))


    return schedulingNotify

    } catch (error: any) {
        console.error('===> Error on CreateSchedulingNotifyService.ts file: \n', error)
        throw new AppError(error.message);
    } 
    
}






// const CreateSchedulingNotifyService = async ({ ticketId, statusChatEndId, schedulingDate, schedulingTime, message }: Request): Promise<SchedulingNotify> => {  

//     const schedulingNotify = await SchedulingNotify.create(
//         {
//             ticketId,
//             statusChatEndId, 
//             schedulingDate, 
//             schedulingTime,
//             message 

//         })

//     return schedulingNotify
//  }

export default CreateSchedulingNotifyService