import { hyphenate, keysToSnakeCase } from "@bigbinary/neeto-cist";
import { BASE_URL, joinHyphenCase } from "@neetoplaywright";

import { CommonUtils } from "@poms/index";
import { OverrideEventLayoutProps } from "@poms/types";
import { CalendarIntegration } from "@types";
import { toSnakeCase } from "@utils";

interface GetSlotsParams {
  meetingName: string;
  bookingMonth: string;
  bookingYear: string;
  timezone: string;
}

export class SchedulingLinkApis {
  private readonly meetingsBaseUrl: string;
  private readonly publicMeetingsBaseUrl: string;

  constructor(private commonUtils: CommonUtils) {
    this.meetingsBaseUrl = `${BASE_URL}/meetings`;
    this.publicMeetingsBaseUrl = `${BASE_URL}/public/meetings`;
  }

  create = (meeting: Record<string, unknown>) =>
    this.commonUtils.apiRequest({
      method: "post",
      url: this.meetingsBaseUrl,
      body: { meeting },
      failOnStatusCode: false,
      timeout: 25_000,
    });

  fetch = (filters, isTemplate: boolean) =>
    this.commonUtils.apiRequest({
      url: this.meetingsBaseUrl,
      params: { filters, is_template: isTemplate },
      failOnStatusCode: false,
    });

  fetchAll = (isTemplate: boolean = false) =>
    this.commonUtils.apiRequest({
      url: this.meetingsBaseUrl,
      params: { is_template: isTemplate },
    });

  update = (meetingId: string, property: Record<string, unknown>) =>
    this.commonUtils.apiRequest({
      method: "put",
      url: `${this.meetingsBaseUrl}/${meetingId}`,
      data: { meeting: property },
    });

  fetchBookingForm = (meetingName: string) =>
    this.commonUtils.apiRequest({
      url: `${this.publicMeetingsBaseUrl}/${joinHyphenCase(meetingName)}`,
    });

  delete = (meetingId: string) =>
    this.commonUtils.apiRequest({
      method: "delete",
      url: `${this.meetingsBaseUrl}/${meetingId}`,
    });

  triggerReminders = (bookingId: string) =>
    this.commonUtils.apiRequest({
      method: "post",
      url: `${BASE_URL}/testing/bookings/reminders/trigger/${bookingId}`,
    });

  getSlots = ({
    meetingName,
    bookingMonth,
    bookingYear,
    timezone,
  }: GetSlotsParams) =>
    this.commonUtils.apiRequest({
      url: `${BASE_URL}/public/slots/${hyphenate(
        meetingName
      )}?year=${bookingYear}&month=${bookingMonth}&timezone=${encodeURIComponent(
        timezone
      )}`,
    });

  overrideEventLayout = (
    meetingId: string,
    { body, customSummary }: OverrideEventLayoutProps,
    calendarIntegration: CalendarIntegration = "googleCalendar"
  ) =>
    this.commonUtils.apiRequest({
      method: "put",
      url: `${this.meetingsBaseUrl}/${meetingId}/${toSnakeCase(`${calendarIntegration}Preferences`)}`,
      data: keysToSnakeCase({
        eventPreferences: {
          body,
          customSummary,
          overrideEventLayout: true,
          summaryType: "custom",
        },
        isTemplate: false,
      }),
    });
}
