/**
 * PaymentRepository
 *
 * 支付 / 付费墙相关远程调用。
 */
import {
  CreatePaymentOrderRequest,
  CreatePaymentOrderResponse,
  PayChannel,
  PaymentOrderStatusResponse,
  PaymentPlansResponse,
} from "@/data/dto/payment";
import { PaymentApi, paymentApi } from "@/data/services/api";
import { PaymentPlansStorage } from "@/data/storage/payment";
import type { IPaymentRepository } from "@/data/repositories/interfaces";
import { Result } from "@/utils/result";
import { createLazySingleton } from "./lazy_singleton";

export class PaymentRepository implements IPaymentRepository {
  constructor(private readonly api: PaymentApi) {}

  /** 获取套餐列表。 */
  async getPlans(): Promise<Result<PaymentPlansResponse>> {
    return Result.wrap(async () => {
      const response = await this.api.getPlans();
      await PaymentPlansStorage.setPlans(response.toJson());
      return response;
    });
  }

  /** 获取本地缓存套餐列表。 */
  async getCachedPlans(): Promise<Result<PaymentPlansResponse | null>> {
    return Result.wrap(async () => {
      const result = await PaymentPlansStorage.getPlans();
      if (Result.isErr(result)) throw result.error;
      return result.data ? PaymentPlansResponse.from(result.data) : null;
    });
  }

  /** 获取咖啡打赏套餐列表，不写入通用套餐缓存。 */
  async getTipPlans(): Promise<Result<PaymentPlansResponse>> {
    return Result.wrap(async () => {
      const response = await this.api.getTipPlans();
      return PaymentPlansResponse.from({
        plans: response.plans.map((plan) => ({
          ...plan.toJson(),
          orderType: "tip",
          vipDays: null,
          dolAmount: null,
          creditBalance: 0,
          originalAmountCents: null,
          dailyPriceCents: null,
          isFirstRechargeOffer: false,
          firstRechargeDiscountPercent: null,
          promotionType: null,
        })),
      });
    });
  }

  /** 清除本地缓存套餐列表。 */
  async clearCachedPlans(): Promise<Result<void>> {
    return Result.wrap(async () => {
      const result = await PaymentPlansStorage.clearPlans();
      if (Result.isErr(result)) throw result.error;
    });
  }

  /** 创建支付订单。 */
  async createOrder(
    planId: string,
    payChannel: PayChannel,
    autoRenew: boolean,
  ): Promise<Result<CreatePaymentOrderResponse>> {
    const request = CreatePaymentOrderRequest.from({
      planId,
      payChannel,
      autoRenew,
    });
    return Result.wrap(() => this.api.createOrder(request));
  }

  /** 查询支付订单状态。 */
  async getOrderStatus(
    orderId: string,
  ): Promise<Result<PaymentOrderStatusResponse>> {
    return Result.wrap(() => this.api.getOrderStatus(orderId));
  }

}

/** 全局懒单例。 */
export const getPaymentRepository = createLazySingleton<IPaymentRepository>(
  () => new PaymentRepository(paymentApi),
);
