var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/server/modules/payment/index.ts
var payment_exports = {};
__export(payment_exports, {
  PaymentServerModule: () => PaymentServerModule
});
module.exports = __toCommonJS(payment_exports);
var import_BaseModule = require("../../../modules/BaseModule");
var WALLET_PASS_CODE = "WALLET_PASS";
var WALLET_DEPENDENT_CODES = /* @__PURE__ */ new Set(["PRODUCTVOUCHER", "GIFTCARD", "POINTCARD"]);
var PAYMENT_METHODS_LOADED_EVENT = "payment:onPaymentMethodsLoaded";
var PaymentServerModule = class extends import_BaseModule.BaseModule {
  constructor(name, version) {
    super(name || "payment", version);
    this.defaultName = "payment";
    this.defaultVersion = "1.0.0";
    this.payMethodMemoryCache = null;
    this.payMethodListInFlight = null;
  }
  async initialize(core, options) {
    var _a, _b, _c;
    this.core = core;
    this.store = options == null ? void 0 : options.store;
    if (!this.store)
      this.store = { payMethods: [] };
    if (!Array.isArray(this.store.payMethods))
      this.store.payMethods = [];
    this.request = core.getPlugin("request");
    const appPlugin = core.getPlugin("app");
    this.app = appPlugin == null ? void 0 : appPlugin.getApp();
    this.logger = (_a = this.app) == null ? void 0 : _a.logger;
    if (!this.request && !((_b = this.app) == null ? void 0 : _b.request)) {
      throw new Error("PaymentServerModule 需要 request 插件或 app.request 支持");
    }
    this.logInfo("PaymentServerModule initialized successfully", {
      hasAppRequest: !!((_c = this.app) == null ? void 0 : _c.request)
    });
  }
  // getRoutes(): RouteDefinition[] {
  //   return [
  //     {
  //       method: 'get',
  //       path: '/pay/custom-payment/all',
  //       handler: async ({ data, config }) => {
  //         const payMethods = await this.getPayMethodListAsync({
  //           shouldFilter: this.shouldFilterPayMethods(data, config),
  //         });
  //         return {
  //           code: 200,
  //           status: true,
  //           data: payMethods,
  //         };
  //       },
  //     },
  //   ];
  // }
  async getPayMethodListAsync(options = {}) {
    var _a;
    this.logInfo("Starting getPayMethodListAsync");
    if ((_a = this.payMethodMemoryCache) == null ? void 0 : _a.length) {
      return this.resolvePayMethods(this.payMethodMemoryCache, options);
    }
    if (this.payMethodListInFlight) {
      const payMethods2 = await this.payMethodListInFlight;
      return this.resolvePayMethods(payMethods2, options);
    }
    this.payMethodListInFlight = this.loadPayMethodListAsync().finally(() => {
      this.payMethodListInFlight = null;
    });
    const payMethods = await this.payMethodListInFlight;
    return this.resolvePayMethods(payMethods, options);
  }
  clearPayMethodCache() {
    this.payMethodMemoryCache = null;
    this.store.payMethods = [];
  }
  async loadPayMethodListAsync() {
    try {
      const payMethods = await this.fetchRemotePayMethods();
      this.setPayMethodCache(payMethods);
      await this.core.effects.emit(PAYMENT_METHODS_LOADED_EVENT, payMethods);
      this.logInfo("getPayMethodListAsync completed successfully", {
        payMethods
      });
      return payMethods;
    } catch (error) {
      console.error("[PaymentServerModule] 获取支付方式列表失败", error);
      this.logError("getPayMethodListAsync failed", error);
      return [];
    }
  }
  async fetchRemotePayMethods() {
    var _a;
    const requester = ((_a = this.app) == null ? void 0 : _a.request) || this.request;
    const response = await requester.get("/shop/pay/custom-payment/all", void 0);
    const payMethods = (response == null ? void 0 : response.data) || response || [];
    return Array.isArray(payMethods) ? payMethods : [];
  }
  shouldFilterPayMethods(data, config) {
    return (data == null ? void 0 : data.filterPaymentMethods) === true || (config == null ? void 0 : config.filterPaymentMethods) === true;
  }
  resolvePayMethods(payMethods, options) {
    if (!options.shouldFilter)
      return payMethods;
    return this.filterPayMethods(payMethods);
  }
  filterPayMethods(payMethods) {
    if (!Array.isArray(payMethods))
      return [];
    let availableMethods = payMethods.filter(
      (method) => method.status === 1 && method.disable === 0
    );
    const walletPassMethod = availableMethods.find(
      (method) => method.code === WALLET_PASS_CODE
    );
    if (!walletPassMethod) {
      return availableMethods.filter(
        (method) => !WALLET_DEPENDENT_CODES.has(method.code)
      );
    }
    availableMethods = availableMethods.map((method) => {
      if (!WALLET_DEPENDENT_CODES.has(method.code))
        return method;
      return {
        ...method,
        channel_application: walletPassMethod.channel_application
      };
    });
    return availableMethods;
  }
  setPayMethodCache(payMethods) {
    this.payMethodMemoryCache = payMethods;
    this.store.payMethods = payMethods;
  }
  logInfo(title, metadata) {
    try {
      if (this.logger) {
        this.logger.addLog({
          type: "info",
          title: `[PaymentServerModule] ${title}`,
          metadata: metadata || {}
        });
      }
    } catch {
    }
  }
  logWarning(title, metadata) {
    try {
      if (this.logger) {
        this.logger.addLog({
          type: "warning",
          title: `[PaymentServerModule] ${title}`,
          metadata: metadata || {}
        });
      }
    } catch {
    }
  }
  logError(title, metadata) {
    try {
      if (this.logger) {
        this.logger.addLog({
          type: "error",
          title: `[PaymentServerModule] ${title}`,
          metadata: metadata || {}
        });
      }
    } catch {
    }
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PaymentServerModule
});
