/**
 * Payment 状态机：Actors（异步服务）
 */
import { fromPromise } from "xstate";

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

export const loadCachedPaymentPlansActor =
  fromPromise<PaymentPlansResponse | null>(async () => {
    const paymentRepo = getPaymentRepository();
    const result = await paymentRepo.getCachedPlans();
    if (Result.isErr(result)) throw result.error;
    return result.data;
  });

export const refreshPaymentPlansActor = fromPromise<PaymentPlansResponse>(
  async () => {
    const paymentRepo = getPaymentRepository();
    const result = await paymentRepo.getPlans();
    if (Result.isErr(result)) throw result.error;
    return result.data;
  },
);

export const createPaymentOrderActor = fromPromise<
  CreatePaymentOrderResponse,
  { planId: string; payChannel: PayChannel; autoRenew: boolean }
>(async ({ input }) => {
  const paymentRepo = getPaymentRepository();
  const result = await paymentRepo.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 paymentRepo = getPaymentRepository();
  const result = await paymentRepo.getOrderStatus(input.orderId);
  if (Result.isErr(result)) throw result.error;
  return result.data;
});
