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

import {
  CreatePaymentOrderResponse,
  PayChannel,
  PaymentOrderStatusResponse,
  PaymentPlansResponse,
  PaymentVipStatusResponse,
} from "@/data/dto/payment";
import { paymentRepository } from "@/data/repositories/payment_repository";
import type { IPaymentRepository } from "@/data/repositories/interfaces";
import { Result } from "@/utils";

const paymentRepo: IPaymentRepository = paymentRepository;

export const loadPaymentPlansActor = fromPromise<PaymentPlansResponse>(
  async () => {
    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 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 result = await paymentRepo.getOrderStatus(input.orderId);
  if (Result.isErr(result)) throw result.error;
  return result.data;
});

export const loadPaymentVipStatusActor =
  fromPromise<PaymentVipStatusResponse>(async () => {
    const result = await paymentRepo.getVipStatus();
    if (Result.isErr(result)) throw result.error;
    return result.data;
  });
