import { keysToSnakeCase } from "@bigbinary/neeto-cist";
import { BASE_URL } from "@neetoplaywright";
import { Dayjs } from "dayjs";

import { STANDARD_DATE_FORMAT } from "@constants/common";
import { CommonUtils } from "@poms/index";
import { BuildHolidayDataProps, UpdateHolidayProps } from "@poms/types";

export class HolidaysApis {
  holidaysBaseUrl = `${BASE_URL}/settings/holidays`;
  private buildHolidayData = ({
    name,
    date,
    isRecurring,
    holidayId,
  }: Partial<BuildHolidayDataProps>) =>
    keysToSnakeCase({
      editingHolidayIds: holidayId ? [holidayId] : [],
      holidays: [
        {
          name,
          holidayOn: date.format(STANDARD_DATE_FORMAT),
          isRecurring,
        },
      ],
    });

  constructor(private commonUtils: CommonUtils) {}

  create = async (name: string, date: Dayjs, isRecurring: boolean = false) => {
    const response = await this.commonUtils.apiRequest({
      url: this.holidaysBaseUrl,
      method: "post",
      data: this.buildHolidayData({ name, date, isRecurring }),
    });

    const { ids: holidayIds } = await response.json();

    return holidayIds;
  };

  update = ({
    holidayId,
    name,
    date,
    isRecurring = false,
  }: UpdateHolidayProps) =>
    this.commonUtils.apiRequest({
      url: this.holidaysBaseUrl,
      method: "post",
      data: this.buildHolidayData({ name, date, isRecurring, holidayId }),
    });

  fetchAll = () => this.commonUtils.apiRequest({ url: this.holidaysBaseUrl });

  delete = (holidayId: string) =>
    this.commonUtils.apiRequest({
      url: `${this.holidaysBaseUrl}/${holidayId}`,
      method: "delete",
      failOnStatusCode: false,
    });
}
