import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { testClient } from 'hono/testing';
import {
  IntegrationTestDatabase,
  setupIntegrationDatabaseHooksWithEntities
} from '@d8d/shared-test-util';
import { PaymentRoutes } from '../../src/routes/payment.routes.js';
import { PaymentEntity } from '../../src/entities/payment.entity.js';
import { PaymentStatus } from '../../src/entities/payment.types.js';
import { UserEntity } from '@d8d/user-module';
import { Role } from '@d8d/user-module';
import { File } from '@d8d/file-module';
import { PaymentService } from '../../src/services/payment.service.js';
import { config } from 'dotenv';
import { resolve } from 'path';
// 导入微信支付SDK用于模拟
import WxPay from 'wechatpay-node-v3';

// 在测试环境中加载环境变量
config({ path: resolve(process.cwd(), '.env.test') });

vi.mock('wechatpay-node-v3')

// 设置集成测试钩子
setupIntegrationDatabaseHooksWithEntities([PaymentEntity, UserEntity, File, Role])

describe('支付回调API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof PaymentRoutes>>;
  let testUser: UserEntity;
  let testPayment: PaymentEntity;

  // 使用真实的微信支付回调数据 - 直接使用原始请求体字符串
  const rawBody = '{"id":"495e231b-9fd8-54a1-8a30-2a38a807744c","create_time":"2025-10-25T12:48:11+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"tl1/8FRRn6g0gRq8IoVR8+95VuIADYBDOt6N9PKiHVhiD6l++W5g/wg6VlsCRIZJ+KWMYTaf5FzQHMjCs8o9otIkLLuJA2aZC+kCQtGxNfyVBwxool/tLT9mHd0dFGThqbj8vb/lm+jjNcmmiWHz+J1ZRvGl7mH4I714vudok7JRt5Q0u0tYaLWr76TTXuQErlA7T4KbeVeGAj8iMpu2ErCpR9QRif36Anc5ARjNYrIWfraXlmUXVbXermDyJ8r4o/4QCFfGk8L1u1WqNYASrRTQvQ8OPqj/J21OkDxbPPrOiEmAX1jOvONvIVEe9Lbkm6rdhW4aLRoZYtiusAk/Vm7MI/UYPwRZbyuc4wwdA1T1D4RdJd/m2I4KSvZHQgs0DM0tLqlb0z3880XYNr8iPFnyu2r8Z8LGcXD+COm06vc7bvNWh3ODwmMrmZQkym/Y/T3X/h/4MZj7+1h2vYHqnnrsgtNPHc/2IwWC/fQlPwtSrLh6iUxSd0betFpKLSq08CaJZvnenpDf1ORRMvd8EhTtIJJ4mV4v+VzCOYNhIcBhKp9XwsuhxIdkpGGmNPpow2c2BXY=","associated_data":"transaction","nonce":"sTnWce32BTQP"}}';
  const callbackHeader = {
    'wechatpay-timestamp': '1761367693',
    'wechatpay-nonce': 'PVDFxrQiJclkR28HpAYPDiIlS2VaGp9U',
    'wechatpay-signature': 'hwR1KKN1bIPAhatIHTen7fwNDyvONS/picpcqSHtUCGkbvhYLVUqC87ksBJs6bovNI0cKNvrLr6gqp/HR4TK/ijgrD6w9W/oYc6bKyO9lNarggsQKHBv5x5yX8OjBOzqtgiHOVj44RCPrglJ5bFDlxIhnhs9jnGUine0qlvrVwBZAylt5X4oFmPammHoV4lLHtGt0L4zr5y6LoZL80LpctDCOCtwC4JdUUY5AumkMYo8lNs+xK0NAN7EVNKCWUzoQ1pVdBTGZWDP+b8+6gswP6JDsL3a4H4Fw3WGh4DZPskDQAe0sn85UGXO3m03OkDq3WkiCkOut4YZMuKBeCBpWA==',
    'wechatpay-serial': '6C2C991E621267BFA5BFD5F32476427343A0B2AD'
  };

  beforeEach(async () => {
    // 创建测试客户端
    client = testClient(PaymentRoutes);

    // 创建测试用户
    const dataSource = await IntegrationTestDatabase.getDataSource();

    const userRepository = dataSource.getRepository(UserEntity);
    testUser = userRepository.create({
      username: `test_user_${Date.now()}`,
      password: 'test_password',
      nickname: '测试用户',
      openid: 'oJy1-16IIG18XZLl7G32k1hHMUFg'
    });
    await userRepository.save(testUser);

    // 创建测试支付记录，使用与真实回调数据一致的金额
    const paymentRepository = dataSource.getRepository(PaymentEntity);
    testPayment = paymentRepository.create({
      externalOrderId: 13, // 与真实回调数据一致
      userId: testUser.id,
      totalAmount: 1, // 1分钱，与真实回调数据一致
      description: '测试支付',
      paymentStatus: PaymentStatus.PROCESSING, // 设置为处理中状态，模拟已发起支付
      openid: testUser.openid!,
      outTradeNo: `ORDER_13_${Date.now()}`
    });
    await paymentRepository.save(testPayment);

    // 手动更新支付记录ID为13，与真实回调数据一致
    await dataSource.query('UPDATE payments SET external_order_id = 13 WHERE id = $1', [testPayment.id]);

    // 设置微信支付SDK的全局mock
    const mockWxPay = {
      transactions_jsapi: vi.fn().mockResolvedValue({
        package: 'prepay_id=wx_test_prepay_id_123456',
        timeStamp: Math.floor(Date.now() / 1000).toString(),
        nonceStr: 'test_nonce_string',
        signType: 'RSA',
        paySign: 'test_pay_sign'
      }),
      verifySign: vi.fn().mockResolvedValue(true),
      decipher_gcm: vi.fn().mockReturnValue(JSON.stringify({
        out_trade_no: testPayment.outTradeNo, // 使用数据库中保存的 outTradeNo
        trade_state: 'SUCCESS',
        transaction_id: 'test_transaction_id',
        amount: {
          total: 1
        }
      })),
      getSignature: vi.fn().mockReturnValue('mock_signature')
    };

    // 模拟PaymentService的wxPay实例
    vi.mocked(WxPay).mockImplementation(() => mockWxPay as any);
  });

  afterEach(() => {
    // 清理 mock
    vi.mocked(WxPay).mockClear();
  });

  describe('POST /payment/callback - 支付回调', () => {
    it('应该成功处理支付成功回调', async () => {
      const response = await client.payment.callback.$post({
        // 使用空的json参数，通过init传递原始请求体
        json: {}
      }, {
        headers: callbackHeader,
        init: {
          body: rawBody
        }
      });

      // 现在支付记录存在，回调处理应该成功
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const result = await response.text();
        expect(result).toBe('SUCCESS');
      }
    });

    it('应该处理支付失败回调', async () => {
      // 使用统一的真实回调数据
      const response = await client.payment.callback.$post({
        // 使用空的json参数，通过init传递原始请求体
        json: {}
      }, {
        headers: callbackHeader,
        init: {
          body: rawBody
        }
      });

      // 由于真实数据是支付成功的，回调处理应该成功
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const result = await response.text();
        expect(result).toBe('SUCCESS');
      }
    });

    it('应该处理无效的回调数据格式', async () => {
      const response = await client.payment.callback.$post({
        body: 'invalid json data'
      }, {
        headers: {
          ...callbackHeader,
          'content-type': 'text/plain'
        }
      });

      // 由于JSON解析失败，应该返回500错误
      expect(response.status).toBe(500);
    });

    it('应该处理缺少必要头信息的情况', async () => {
      const response = await client.payment.callback.$post({
        body: rawBody
      }, {
        headers: {
          // 缺少必要的微信支付头信息
          'Content-Type': 'text/plain'
        }
      });

      // 由于缺少必要头信息，应该返回500错误
      expect(response.status).toBe(500);
    });

    it('应该验证回调数据解密后的支付处理', async () => {
      const response = await client.payment.callback.$post({
        // 使用空的json参数，通过init传递原始请求体
        json: {}
      }, {
        headers: callbackHeader,
        init: {
          body: rawBody
        }
      });

      // 现在支付记录存在，回调处理应该成功
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const result = await response.text();
        expect(result).toBe('SUCCESS');
      }
    });
  });
});