import { fromPromise } from "xstate";

import {
  CreatePaymentOrderResponse,
  PayChannel,
  PaymentOrderStatusResponse,
} from "@/data/dto/payment";
import { getPaymentRepository } from "@/data/repositories/payment_repository";
import { Result } from "@/utils/result";

export const createPaymentOrderActor = fromPromise<
  CreatePaymentOrderResponse,
  { planId: string; payChannel: PayChannel; autoRenew: boolean }
>(async ({ input }) => {
  const result = await getPaymentRepository().createOrder(
    input.planId,
    input.payChannel,
    input.autoRenew,
  );
  if (Result.isErr(result)) throw result.error;
  return result.data;
});

export const pollPaymentOrderStatusActor = fromPromise<
  PaymentOrderStatusResponse,
  { orderId: string }
>(async ({ input }) => {
  const result = await getPaymentRepository().getOrderStatus(input.orderId);
  if (Result.isErr(result)) throw result.error;
  return result.data;
});
