import AppError from "../../errors/AppError";
import SettingTicket from "../../models/SettingTicket";

interface Request {
  key: string;
  startTime: string;
  endTime: string;
  value: string;
  message: string;
  number: string;
}

const updateSettingTicket = async ({
  key,
  startTime,
  endTime,
  value,
  message,
  number
}: Request): Promise<SettingTicket | undefined> => {
  try {
    let businessHours = await SettingTicket.findOne({ where: { key, number } });

    if (!businessHours) {
      // throw new AppError("ERR_NO_SETTING_FOUND", 404);

      businessHours = await SettingTicket.create({
        key,
        startTime,
        endTime,
        value,
        message,
        number
      });
      return businessHours;
    }

    await businessHours.update(
      { startTime, endTime, message, value, number },
      { where: { key, number } }
    );

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

export default updateSettingTicket;
