import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { authMiddleware } from '../../middleware/auth.middleware';
import { PaymentService } from '../../modules/payment/payment.service';
import { AuthContext } from '../../types/context';
import { ErrorSchema } from '../../utils/errorHandler';

// 支付创建请求Schema
const PaymentCreateSchema = z.object({
  orderId: z.number().int().positive().describe('订单ID'),
  totalAmount: z.number().int().positive().describe('支付金额（分）'),
  description: z.string().min(1).max(128).describe('支付描述')
});

// 支付创建响应Schema
const PaymentCreateResponseSchema = z.object({
  paymentId: z.string().describe('支付ID'),
  timeStamp: z.string().describe('时间戳'),
  nonceStr: z.string().describe('随机字符串'),
  package: z.string().describe('预支付ID'),
  signType: z.string().describe('签名类型'),
  paySign: z.string().describe('签名'),
  totalAmount: z.number().int().positive().describe('支付金额（分）') // 添加金额字段用于前端验证
});

// 支付回调请求Schema
const PaymentCallbackSchema = z.object({
  id: z.string().describe('通知ID'),
  create_time: z.string().describe('创建时间'),
  event_type: z.string().describe('事件类型'),
  resource_type: z.string().describe('资源类型'),
  resource: z.object({
    algorithm: z.string().describe('加密算法'),
    ciphertext: z.string().describe('密文'),
    associated_data: z.string().optional().describe('附加数据'),
    nonce: z.string().describe('随机串')
  }).describe('回调资源'),
  summary: z.string().describe('摘要')
});

// 支付创建路由定义
const createPaymentRoute = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: PaymentCreateSchema }
      }
    }
  },
  responses: {
    200: {
      description: '支付创建成功',
      content: { 'application/json': { schema: PaymentCreateResponseSchema } }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '未授权',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 支付回调路由定义
const paymentCallbackRoute = createRoute({
  method: 'post',
  path: '/callback',
  request: {
    body: {
      content: {
        'text/plain': { schema: z.string() }
      }
    }
  },
  responses: {
    200: {
      description: '回调处理成功',
      content: { 'text/plain': { schema: z.string() } }
    },
    400: {
      description: '回调数据错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'text/plain': { schema: z.string() } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  .openapi(createPaymentRoute, async (c) => {
    try {
      const user = c.get('user');
      const paymentData = c.req.valid('json');

      // 创建支付服务实例
      const paymentService = new PaymentService();

      // 检查用户是否有openid（小程序用户必需）
      if (!user.openid) {
        return c.json({
          code: 400,
          message: '用户未绑定微信小程序，无法进行支付'
        }, 400);
      }

      // 创建支付订单，从认证用户中获取openid
      const paymentResult = await paymentService.createPayment(
        paymentData.orderId,
        paymentData.totalAmount,
        paymentData.description,
        user.openid
      );

      return c.json(paymentResult, 200);
    } catch (error) {
      console.error('支付创建失败:', error);
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '支付创建失败'
      }, 500);
    }
  })
  .openapi(paymentCallbackRoute, async (c) => {
    try {
      // 获取原始请求体（用于签名验证）
      const rawBody = await c.req.text();

      console.log('原始请求体', rawBody)

      // 解析回调数据
      const callbackData = JSON.parse(rawBody);

      // 获取微信支付回调头信息
      const headers = {
        'wechatpay-timestamp': c.req.header('wechatpay-timestamp') || '',
        'wechatpay-nonce': c.req.header('wechatpay-nonce') || '',
        'wechatpay-signature': c.req.header('wechatpay-signature') || '',
        'wechatpay-serial': c.req.header('wechatpay-serial') || ''
      };

      // 创建支付服务实例
      const paymentService = new PaymentService();

      // 处理支付回调
      await paymentService.handlePaymentCallback(callbackData, headers, rawBody);

      // 返回成功响应给微信支付
      return c.text('SUCCESS', 200);
    } catch (error) {
      console.error('支付回调处理失败:', error);
      // 返回失败响应给微信支付
      return c.text('FAIL', 500);
    }
  });

export default app;