/**
 * PaymentRepository
 *
 * 统一封装默认套餐、Tip 套餐、订单创建和订单状态查询。
 */
import type { IPaymentRepository } from "@/data/repositories/interfaces";
import {
  CreatePaymentOrderRequestSchema,
  CreatePaymentOrderResponse,
  GiftProductsResponse,
  PayChannel,
  PaymentOrderStatusResponse,
  PaymentPlansResponse,
  PaymentPlansResponseSchema,
  TipMessageRequestSchema,
  TipMessageResponse,
} from "@/data/schemas/payment";
import { PaymentApi, paymentApi } from "@/data/services/api";
import { PaymentPlansStorage } from "@/data/storage/payment";
import { Result } from "@/utils/result";
import { createLazySingleton } from "./lazy_singleton";

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

  /** 获取套餐列表。 */
  async getPlans(
    commercialOfferId?: string,
    supportCharacterId?: string,
  ): Promise<Result<PaymentPlansResponse>> {
    return Result.wrap(async () => {
      const response = await this.api.getPlans(
        commercialOfferId,
        supportCharacterId,
      );
      if (!commercialOfferId && !supportCharacterId) {
        await PaymentPlansStorage.setPlans(response);
      }
      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 ? PaymentPlansResponseSchema.parse(result.data) : null;
    });
  }

  /** 获取当前角色的完整礼物目录，不写入订阅套餐缓存。 */
  async getGiftProducts(
    characterId: string,
  ): Promise<Result<GiftProductsResponse>> {
    return Result.wrap(() => this.api.getGiftProducts(characterId));
  }

  /** 清除本地缓存套餐列表。 */
  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,
    recipientCharacterId?: string,
    commercialOfferId?: string,
    chatActionId?: string,
  ): Promise<Result<CreatePaymentOrderResponse>> {
    const request = CreatePaymentOrderRequestSchema.parse({
      planId,
      payChannel,
      autoRenew,
      ...(recipientCharacterId ? { recipientCharacterId } : {}),
      ...(commercialOfferId ? { commercialOfferId } : {}),
      ...(chatActionId ? { chatActionId } : {}),
    });
    return Result.wrap(() => this.api.createOrder(request));
  }

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

  /** 获取已支付礼物订单的角色感谢文案。 */
  async getTipMessage(orderId: string): Promise<Result<TipMessageResponse>> {
    const request = TipMessageRequestSchema.parse({ orderId });
    return Result.wrap(() => this.api.getTipMessage(request));
  }
}

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