"use client";

/**
 * PaymentRepository
 *
 * 支付 / 付费墙相关远程调用。
 */
import {
  CreatePaymentOrderRequest,
  CreatePaymentOrderResponse,
  PayChannel,
  PaymentOrderStatusResponse,
  PaymentPlan,
  PaymentPlansResponse,
  PaymentVipStatusResponse,
} 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 getVipPlans(): Promise<Result<PaymentPlan[]>> {
    return Result.wrap(async () => {
      const response = await this.api.getPlans();
      return response.plans.filter(isVipPaymentPlan);
    });
  }

  /** 获取积分套餐列表。 */
  async getCreditPlans(): Promise<Result<PaymentPlan[]>> {
    return Result.wrap(async () => {
      const response = await this.api.getPlans();
      return response.plans.filter(isCreditPaymentPlan);
    });
  }

  /** 创建支付订单。 */
  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));
  }

  /** 查询当前用户 VIP 状态。 */
  async getVipStatus(): Promise<Result<PaymentVipStatusResponse>> {
    return Result.wrap(() => this.api.getVipStatus());
  }
}

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

export function isVipPaymentPlan(plan: PaymentPlan): boolean {
  return plan.vipDays !== null;
}

export function isCreditPaymentPlan(plan: PaymentPlan): boolean {
  return plan.dolAmount !== null;
}
