import { CampaignStatuses } from "@komi-app/components";
import { dcaBaseUrl } from "constants/dca";
import { CampaignStatus } from "types/campaigns";
import { parseUrlParamsToSuffix } from "utils/url";

import { FLAGS, isOn, isReady } from "@komi-app/flags-sdk";

export function toCampaignStatuses(
  status: CampaignStatus,
  startTimestamp: number | null,
): CampaignStatuses {
  const statusMap = {
    [CampaignStatus.Draft]: CampaignStatuses.DRAFT,
    [CampaignStatus.Scheduled]: CampaignStatuses.SCHEDULED,
    [CampaignStatus.Sending]: CampaignStatuses.SENDING,
    [CampaignStatus.Completed]: CampaignStatuses.COMPLETED,
    [CampaignStatus.Stopped]: CampaignStatuses.STOPPED,
  };

  if (!isReady() || !startTimestamp) return statusMap[status];

  /**
   * this code is a refactor to make campaign statuses consistent everywhere they are displayed.
   *
   * prev comment said:
   * mark it as 'sending' if it's completed and isn't due time.
   * this is a short term fix until we sort out the backend and how we mark campaigns
   *
   * and another from campaign utils said:
   * Convert status to Sending if status is Scheduled and scheduledSendTimestamp is in the past
   */

  const currentTime = Date.now();
  const startTime = new Date(startTimestamp).getTime();
  const isPastDateTime = startTime < currentTime;

  switch (status) {
    case CampaignStatus.Completed: {
      return statusMap[status];
    }
    case CampaignStatus.Scheduled: {
      if (isPastDateTime) {
        return statusMap[CampaignStatus.Sending];
      }
      return statusMap[status];
    }
  }

  return statusMap[status];
}

export const createCampaignEditUrl = (campaignId: string, type = "") => {
  const searchParams = parseUrlParamsToSuffix({ campaignId, type });
  return `${dcaBaseUrl}/campaign-edit${searchParams}`;
};
export const createNewCampaignWithSegment = (segmentId: string) => {
  const searchParams = parseUrlParamsToSuffix({ segmentId });
  return `${dcaBaseUrl}/campaign-create${searchParams}`;
};
export const createCampaignReportUrl = (campaignId: string) => {
  const searchParams = parseUrlParamsToSuffix({ campaignId });
  return `${dcaBaseUrl}/campaign-report${searchParams}`;
};
export const createEmailCampaignReportUrl = (campaignId: string) => {
  const searchParams = parseUrlParamsToSuffix({ campaignId });
  return `${dcaBaseUrl}/email-campaign-report${searchParams}`;
};

export const createEditSMSCampaignURL = (campaignId: string) => {
  const searchParams = parseUrlParamsToSuffix({ campaignId });
  return `${dcaBaseUrl}/sms-campaign-edit${searchParams}`;
};
