import { fromPromise } from "xstate";

import { PaymentPlansResponse } from "@/data/dto/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 }
>(async ({ input }) => {
  if (input.catalog === "tip") return null;
  const result = await getPaymentRepository().getCachedPlans();
  if (Result.isErr(result)) throw result.error;
  return result.data;
});

export const refreshPaymentPlansActor = fromPromise<
  PaymentPlansResponse,
  { catalog: PaymentPlanCatalog }
>(async ({ input }) => {
  const paymentRepo = getPaymentRepository();
  const result =
    input.catalog === "tip"
      ? await paymentRepo.getTipPlans()
      : await paymentRepo.getPlans();
  if (Result.isErr(result)) throw result.error;
  return result.data;
});
