import { fromPromise } from "xstate";

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

export const createPaymentOrderActor = fromPromise<
  CreatePaymentOrderResponse,
  {
    planId: string;
    payChannel: PayChannel;
    autoRenew: boolean;
    recipientCharacterId?: string;
    commercialOfferId?: string;
    chatActionId?: string;
  }
>(async ({ input }) => {
  const result = await getPaymentRepository().createOrder(
    input.planId,
    input.payChannel,
    input.autoRenew,
    input.recipientCharacterId,
    input.commercialOfferId,
    input.chatActionId,
  );
  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;
});
