import {
  PaymentPlanSchema,
  type GiftProduct,
  type GiftProductsResponse,
  type PaymentPlan,
} from "@/data/schemas/payment";

import type { PaymentState } from "../payment-state";

export function giftProductToPaymentPlan(
  product: GiftProduct,
): PaymentPlan {
  return PaymentPlanSchema.parse({
    planId: product.planId,
    planName: product.planName,
    orderType: product.orderType,
    vipDays: null,
    dolAmount: null,
    creditBalance: 0,
    amountCents: product.amountCents,
    originalAmountCents: null,
    dailyPriceCents: null,
    currency: product.currency,
    isFirstRechargeOffer: false,
    mostPopular: false,
    firstRechargeDiscountPercent: null,
    promotionType: product.promotionType,
  });
}

export function hydrateGiftProductsState(
  response: GiftProductsResponse,
  characterId: string,
  restoredCategory: string | null,
  restoredPlanId: string | null,
): Pick<
  PaymentState,
  | "plans"
  | "giftCategories"
  | "giftProducts"
  | "selectedGiftCategory"
  | "selectedPlanId"
  | "requestedGiftCategory"
  | "requestedGiftPlanId"
  | "autoRenew"
  | "isFirstRecharge"
  | "errorMessage"
> {
  const giftCategories = response.categories;
  const giftProducts = response.plans.filter(
    (product) => product.characterId === characterId,
  );
  const restoredProduct = restoredPlanId
    ? giftProducts.find((product) => product.planId === restoredPlanId)
    : null;
  const selectedGiftCategory =
    restoredProduct?.category ??
    (restoredCategory &&
    giftCategories.some((category) => category.category === restoredCategory)
      ? restoredCategory
      : (giftCategories[0]?.category ?? null));
  const visibleProducts = selectedGiftCategory
    ? giftProducts.filter(
        (product) => product.category === selectedGiftCategory,
      )
    : [];
  const canRestoreSelection = visibleProducts.some(
    (product) => product.planId === restoredPlanId,
  );
  const selectedPlanId = canRestoreSelection
    ? (restoredPlanId ?? "")
    : (visibleProducts[0]?.planId ?? "");

  return {
    plans: visibleProducts.map(giftProductToPaymentPlan),
    giftCategories,
    giftProducts,
    selectedGiftCategory,
    selectedPlanId,
    requestedGiftCategory: null,
    requestedGiftPlanId: null,
    autoRenew: false,
    isFirstRecharge: false,
    errorMessage: null,
  };
}

export function getSelectedGiftProduct(
  context: Pick<PaymentState, "giftProducts" | "selectedPlanId">,
): GiftProduct | null {
  return (
    context.giftProducts.find(
      (product) => product.planId === context.selectedPlanId,
    ) ?? null
  );
}
