import {
  MAIL_GROWTH_PLAN_CHARGE_PER_MEMBER,
  MAIL_GROWTH_PLAN_NET_PRICE_PER_MEMBER,
} from "@/lib/pricing";
import { formatPolarPrice } from "@/lib/billing-region";

export const MAIL_GROWTH_PLAN_PRICE_PER_MEMBER = MAIL_GROWTH_PLAN_NET_PRICE_PER_MEMBER;

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;
  billingSeatCount: number;
  billingStatus: MailPlanBillingStatus;
  description: string;
  currency: string;
  estimatedMonthlyCost: number;
  estimatedMonthlyCostLabel: string;
  isComplimentary: boolean;
  label: string;
  priceIncludesVat: boolean;
  taxLabel: string;
  tier: MailPlanTier;
  unitPrice: number;
  unitPriceLabel: string;
};

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;
  locale?: string;
  localizedPrice?: {
    amount: number;
    currency: string;
  } | null;
  seatChargeAmount?: number | null;
}): MailPlanSummary {
  const billingSeatCount = Math.max(1, Math.floor(input.billingSeatCount));
  const isComplimentary = Boolean(input.isComplimentary);
  const currency = input.localizedPrice?.currency ?? "krw";
  const unitPrice = input.localizedPrice?.amount ?? MAIL_GROWTH_PLAN_PRICE_PER_MEMBER;
  const estimatedMonthlyCost = isComplimentary ? 0 : billingSeatCount * unitPrice;
  const unitPriceLabel = formatPolarPrice(unitPrice, currency, input.locale ?? "ko");
  const estimatedMonthlyCostLabel = formatPolarPrice(
    estimatedMonthlyCost,
    currency,
    input.locale ?? "ko",
  );
  const growthPlanActive = isComplimentary || input.billingStatus === "active";
  const priceIncludesVat = false;
  const taxLabel = currency === "krw"
    ? "VAT 별도"
    : "세금은 결제 단계에서 계산";

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

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

export function createMailBillingPreview(
  seatCount: number,
  seatChargeAmount?: number | null,
): MailBillingPreview {
  const billableSeats = Math.max(1, Math.floor(seatCount));
  const estimatedMonthlyCost =
    billableSeats * resolveMailBillingSeatChargeAmount(seatChargeAmount);

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

export function createMailBillingChargeSummary(
  seatCount: number,
  seatChargeAmount?: number | null,
): MailBillingChargeSummary {
  const billableSeats = Math.max(1, Math.floor(seatCount));
  const estimatedMonthlyCost =
    billableSeats * resolveMailBillingSeatChargeAmount(seatChargeAmount);

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

export function resolveMailBillingSeatChargeAmount(value?: number | null) {
  return typeof value === "number" && Number.isFinite(value) && value > 0
    ? Math.floor(value)
    : MAIL_GROWTH_PLAN_CHARGE_PER_MEMBER;
}
