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

interface Request {
  key: string;
  value: string;
  obj?: string;
}

const UpdateSettingService = async ({
  key,
  value,
  obj
}: Request): Promise<Setting | undefined> => {
  console.log("key: ", key, " | value: ", value, " | obj: ", obj);

  try {
    const setting = await Setting.findOne({
      where: { key }
    });

    if (!setting) {
      throw new AppError("ERR_NO_SETTING_FOUND", 404);
    }

    if (obj) {
      obj = JSON.stringify(obj);
    }
    await setting.update({ value, obj });

    await setting.reload();

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

export default UpdateSettingService;
