import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';

export interface PaymentConfig {
  wxpay: {
    appId: string;
    mchId: string;
    apiKey: string;
    certPath: string;
    keyPath: string;
    notifyUrl: string;
    mock: boolean;
  };
  alipay: {
    appId: string;
    privateKey: string;
    alipayPublicKey: string;
    notifyUrl: string;
    returnUrl: string;
    gateway: string;
    mock: boolean;
  };
}

@Injectable()
export class PaymentConfigService {
  private readonly logger = new Logger(PaymentConfigService.name);
  private cache: PaymentConfig | null = null;

  constructor(private prisma: PrismaService) {}

  async load(): Promise<PaymentConfig> {
    if (this.cache) return this.cache;
    return this.refresh();
  }

  async refresh(): Promise<PaymentConfig> {
    const all = await this.prisma.systemConfig.findMany({
      where: { category: 'payment' },
    });
    const map = new Map(all.map(c => [c.key, c.value]));

    const conf: PaymentConfig = {
      wxpay: {
        appId: map.get('wx_appid') || process.env.WX_APPID || '',
        mchId: map.get('wx_mchid') || process.env.WX_MCHID || process.env.WX_PAY_MCH_ID || '1108945993',
        apiKey: map.get('wx_apikey') || process.env.WX_API_KEY || process.env.WX_PAY_API_KEY || '8Kj9mP2nQ5rT7vW1xY3zA4bC6dE8fG0h',
        certPath: map.get('wx_cert_path') || process.env.WX_CERT_PATH || '',
        keyPath: map.get('wx_key_path') || process.env.WX_KEY_PATH || '',
        notifyUrl: map.get('wx_notify_url') || process.env.WX_NOTIFY_URL || 'https://yuzhiran.com/api/v1/payment/wxpay/notify',
        mock: (map.get('wx_mock') || process.env.WX_PAY_MOCK || 'true') === 'true',
      },
      alipay: {
        appId: map.get('alipay_app_id') || process.env.ALIPAY_APP_ID || '',
        privateKey: map.get('alipay_private_key') || process.env.ALIPAY_PRIVATE_KEY || '',
        alipayPublicKey: map.get('alipay_public_key') || process.env.ALIPAY_PUBLIC_KEY || '',
        notifyUrl: map.get('alipay_notify_url') || process.env.ALIPAY_NOTIFY_URL || 'https://yuzhiran.com/api/v1/payment/alipay/notify',
        returnUrl: map.get('alipay_return_url') || process.env.ALIPAY_RETURN_URL || 'https://yuzhiran.com/my/member',
        gateway: map.get('alipay_gateway') || process.env.ALIPAY_GATEWAY || 'https://openapi.alipay.com/gateway.do',
        mock: (map.get('alipay_mock') || process.env.ALIPAY_MOCK || 'true') === 'true',
      },
    };

    this.cache = conf;
    this.logger.log(`支付配置已加载 (微信mock:${conf.wxpay.mock}, 支付宝mock:${conf.alipay.mock})`);
    return conf;
  }

  invalidateCache() {
    this.cache = null;
  }
}
