/**
 * Payment API
 *
 * 付费墙 / 充值相关接口
 */
import {
  CreatePaymentOrderRequest,
  CreatePaymentOrderResponse,
  PaymentOrderStatusResponse,
  PaymentPlansResponse,
  PaymentVipStatusResponse,
} from "@/data/dto/payment";

import { ApiPath } from "./api_path";
import { httpClient } from "./http_client";
import { ApiEnvelope, unwrap } from "./response_helper";

export class PaymentApi {
  /**
   * 获取套餐列表
   */
  async getPlans(): Promise<PaymentPlansResponse> {
    const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.paymentPlans);
    return PaymentPlansResponse.fromJson(
      unwrap(env) as Record<string, unknown>,
    );
  }

  /**
   * 创建支付订单
   */
  async createOrder(
    body: CreatePaymentOrderRequest,
  ): Promise<CreatePaymentOrderResponse> {
    const env = await httpClient<ApiEnvelope<unknown>>(
      ApiPath.paymentCreateOrder,
      {
        method: "POST",
        body: body.toJson(),
      },
    );
    return CreatePaymentOrderResponse.fromJson(
      unwrap(env) as Record<string, unknown>,
    );
  }

  /**
   * 查询支付订单状态
   */
  async getOrderStatus(
    orderId: string,
  ): Promise<PaymentOrderStatusResponse> {
    const env = await httpClient<ApiEnvelope<unknown>>(
      ApiPath.paymentOrderStatus,
      {
        query: { order_id: orderId },
      },
    );
    return PaymentOrderStatusResponse.fromJson(
      unwrap(env) as Record<string, unknown>,
    );
  }

  /**
   * 查询当前用户 VIP 状态
   */
  async getVipStatus(): Promise<PaymentVipStatusResponse> {
    const env = await httpClient<ApiEnvelope<unknown>>(
      ApiPath.paymentVipStatus,
    );
    return PaymentVipStatusResponse.fromJson(
      unwrap(env) as Record<string, unknown>,
    );
  }
}

/**
 * 全局单例
 */
export const paymentApi = new PaymentApi();
