export const MAIL_GROWTH_PLAN_PRICE_PER_MEMBER = 3900;

const COMPLIMENTARY_GROWTH_PLAN_EMAILS = new Set([
  "admin@officialsite.kr",
  ...(process.env.MAIL_COMPLIMENTARY_GROWTH_EMAILS ?? "")
    .split(",")
    .map((email) => email.trim().toLowerCase())
    .filter(Boolean),
]);

export type MailPlanBillingStatus = "pending" | "active" | "paused" | "cancelled" | null;
export type MailPlanTier = "free" | "growth";

export type MailPlanSummary = {
  aiAssistAvailable: boolean;
  badgeLabel: string;
  billingStatus: MailPlanBillingStatus;
  description: string;
  estimatedMonthlyCost: number;
  isComplimentary: boolean;
  label: string;
  tier: MailPlanTier;
};

export type MailBillingPreview = {
  billableSeats: number;
  chargeAmount: number;
  estimatedMonthlyCost: number;
  usesFallbackAmount: boolean;
};

export type MailBillingChargeSummary = {
  amount: number;
  billableSeats: number;
  estimatedMonthlyCost: number;
  isChargeable: boolean;
};

export function countMailBillingSeatsFromManagedMembers(managedMemberCount: number) {
  const normalizedManagedMemberCount = Math.max(0, Math.floor(managedMemberCount));
  return normalizedManagedMemberCount + 1;
}

export function hasComplimentaryGrowthPlanByEmail(email: string | null | undefined) {
  return COMPLIMENTARY_GROWTH_PLAN_EMAILS.has(email?.trim().toLowerCase() ?? "");
}

export function createMailPlanSummary(input: {
  billingSeatCount: number;
  billingStatus: MailPlanBillingStatus;
  isComplimentary?: boolean;
}): MailPlanSummary {
  const billingSeatCount = Math.max(1, Math.floor(input.billingSeatCount));
  const isComplimentary = Boolean(input.isComplimentary);
  const estimatedMonthlyCost = isComplimentary
    ? 0
    : billingSeatCount * MAIL_GROWTH_PLAN_PRICE_PER_MEMBER;
  const growthPlanActive = isComplimentary || input.billingStatus === "active";

  if (growthPlanActive) {
    return {
      aiAssistAvailable: true,
      badgeLabel: isComplimentary ? "운영 혜택 적용" : "현재 이용 중",
      billingStatus: input.billingStatus,
      description:
        isComplimentary
          ? "운영 계정 혜택으로 결제수단 등록과 멤버 과금 없이 성장 플랜 기능을 사용할 수 있습니다."
          : `AI 어시스트와 팀 확장을 사용 중이며, 팀 인원 ${billingSeatCount}명 기준으로 월 ${estimatedMonthlyCost.toLocaleString(
              "ko-KR",
            )}원이 반영됩니다.`,
      estimatedMonthlyCost,
      isComplimentary,
      label: "성장 플랜",
      tier: "growth",
    };
  }

  return {
    aiAssistAvailable: false,
    badgeLabel: "현재 무료",
    billingStatus: input.billingStatus,
    description:
      `무료 플랜에서는 대표 메일 1개를 비용 없이 사용할 수 있습니다. 성장 플랜을 시작하면 팀 인원 ${billingSeatCount}명 기준으로 월 ${estimatedMonthlyCost.toLocaleString(
        "ko-KR",
      )}원이 적용됩니다.`,
    estimatedMonthlyCost,
    isComplimentary: false,
    label: "무료 플랜",
    tier: "free",
  };
}

export function createMailBillingPreview(seatCount: number): MailBillingPreview {
  const billableSeats = Math.max(1, Math.floor(seatCount));
  const estimatedMonthlyCost = billableSeats * MAIL_GROWTH_PLAN_PRICE_PER_MEMBER;

  return {
    billableSeats,
    estimatedMonthlyCost,
    chargeAmount: estimatedMonthlyCost,
    usesFallbackAmount: false,
  };
}

export function createMailBillingChargeSummary(seatCount: number): MailBillingChargeSummary {
  const billableSeats = Math.max(1, Math.floor(seatCount));
  const estimatedMonthlyCost = billableSeats * MAIL_GROWTH_PLAN_PRICE_PER_MEMBER;

  return {
    amount: estimatedMonthlyCost,
    billableSeats,
    estimatedMonthlyCost,
    isChargeable: true,
  };
}
