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" | "giftOffer" | "giftProducts" | "selectedGiftCategory" | "selectedPlanId" | "requestedGiftCategory" | "requestedGiftPlanId" | "autoRenew" | "isFirstRecharge" | "errorMessage" > { const giftCategories = response.categories; const giftProducts = response.plans.filter( (product) => product.characterId === characterId, ); const selectedGiftCategory = giftCategories[0]?.category ?? null; const visibleProducts = selectedGiftCategory ? giftProducts.filter( (product) => product.category === selectedGiftCategory, ) : []; const canRestoreSelection = restoredCategory === selectedGiftCategory && visibleProducts.some((product) => product.planId === restoredPlanId); const selectedPlanId = canRestoreSelection ? (restoredPlanId ?? "") : (visibleProducts[0]?.planId ?? ""); return { plans: visibleProducts.map(giftProductToPaymentPlan), giftCategories, giftOffer: response.offer, giftProducts, selectedGiftCategory, selectedPlanId, requestedGiftCategory: null, requestedGiftPlanId: null, autoRenew: false, isFirstRecharge: false, errorMessage: null, }; } export function getSelectedGiftProduct( context: Pick, ): GiftProduct | null { return ( context.giftProducts.find( (product) => product.planId === context.selectedPlanId, ) ?? null ); }