import {
  BaseCampaignPayload,
  EMAIL_CAMPAIGN_DEFAULT_FORM_VALUES,
  EmailCampaignForm,
  EmailCampaignPayload,
  ZEmailCampaignForm,
} from "@komi-app/messaging-sdk";
import { FormErrors } from "types/campaigns";

import moment from "moment";

export const formErrors = <T extends Record<string, unknown>>(
  obj: T,
): FormErrors<T> => {
  const result = ZEmailCampaignForm.required().safeParse(obj);

  if (result.success) return {};
  const { fieldErrors } = result.error.flatten();

  const errors: FormErrors<T> = {};

  for (const key in fieldErrors) {
    if (fieldErrors[key as keyof typeof fieldErrors]?.length) {
      errors[key as keyof T] =
        fieldErrors[key as keyof typeof fieldErrors]?.[0];
    }
  }

  return errors;
};

export const payloadToForm = async (
  payload: BaseCampaignPayload<EmailCampaignPayload>,
): Promise<Partial<EmailCampaignForm>> => {
  const date = payload.scheduledTimestamp;

  return {
    acceptedTerms: false,
    campaignTemplateId: payload.campaignTemplateId,
    name: payload.name,
    initialSize: payload.initialSize,
    priority: payload.priority,
    ...(date && {
      scheduledDate: date,
      scheduledHour: Number(moment(date).format("h")),
      scheduledMinute: Number(moment(date).format("m")),
      scheduledPeriod: moment(date).format("A"),
    }),
    scheduledTimezone: payload.scheduledTimezone,
    scheduleType: payload.scheduleType,
    segmentIds: payload.segmentIds,
    subject: payload.subject,
  };
};

export const formToPayload = (
  form: Partial<EmailCampaignForm>,
): BaseCampaignPayload<EmailCampaignPayload> => {
  const {
    scheduledDate,
    scheduledHour,
    scheduledMinute,
    scheduledPeriod,
    scheduledTimezone,
    ...rest
  } = form;

  let date = undefined;

  if (
    scheduledDate &&
    Number.isInteger(scheduledHour) &&
    Number.isInteger(scheduledMinute) &&
    scheduledPeriod &&
    scheduledTimezone
  ) {
    // 12-hour to 24-hour conversion
    const hour =
      scheduledPeriod === "AM"
        ? Number(scheduledHour) % 12
        : (Number(scheduledHour) % 12) + 12;

    date = moment.tz(
      {
        year: scheduledDate.getFullYear(),
        month: scheduledDate.getMonth(),
        day: scheduledDate.getDate(),
        hour,
        minute: scheduledMinute,
      },
      scheduledTimezone,
    );
  }

  return {
    ...EMAIL_CAMPAIGN_DEFAULT_FORM_VALUES,
    ...rest,
    scheduledTimestamp: date?.toDate() || null,
  };
};
