import { fromPromise } from "xstate";

import { PaymentPlansResponse } from "@/data/schemas/payment";
import { getPaymentRepository } from "@/data/repositories/payment_repository";
import { Result } from "@/utils/result";

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

export const loadCachedPaymentPlansActor = fromPromise<
  PaymentPlansResponse | null,
  { catalog: PaymentPlanCatalog; commercialOfferId?: string | null; supportCharacterId?: string | null }
>(async ({ input }) => {
  if (input.catalog === "tip" || input.commercialOfferId || input.supportCharacterId) return null;
  const result = await getPaymentRepository().getCachedPlans();
  if (Result.isErr(result)) throw result.error;
  return result.data;
});

export const refreshPaymentPlansActor = fromPromise<
  PaymentPlansResponse,
  { catalog: PaymentPlanCatalog; commercialOfferId?: string | null; supportCharacterId?: string | null }
>(async ({ input }) => {
  const paymentRepo = getPaymentRepository();
  if (input.catalog === "tip") {
    throw new Error("Gift catalogs must use the gift products actor.");
  }
  const result = await paymentRepo.getPlans(
    input.commercialOfferId ?? undefined,
    input.supportCharacterId ?? undefined,
  );
  if (Result.isErr(result)) throw result.error;
  return result.data;
});
