import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { ConsultationRequestSchema, CreateConsultationRequestDto } from '@/server/modules/consultation/consultation-request.schema';
import { ErrorSchema } from '@/server/utils/errorHandler';
import { AppDataSource } from '@/server/data-source';
import { ConsultationRequestService } from '@/server/modules/consultation/consultation-request.service';

// 响应Schema
const CreateResponse = z.object({
  success: z.boolean().openapi({ description: '是否成功', example: true }),
  message: z.string().openapi({ description: '响应消息', example: '客户需求提交成功' }),
  data: ConsultationRequestSchema.optional().openapi({ description: '创建的客户需求数据' })
});

// 路由定义
const routeDef = createRoute({
  method: 'post',
  path: '/',
  // 注意：不使用authMiddleware，支持游客提交
  request: {
    body: {
      content: {
        'application/json': { schema: CreateConsultationRequestDto }
      }
    }
  },
  responses: {
    200: {
      description: '成功提交客户需求',
      content: { 'application/json': { schema: CreateResponse } }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    429: {
      description: '提交频率过高',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 路由实现
const app = new OpenAPIHono().openapi(routeDef, async (c) => {
  try {
    const data = await c.req.json();
    const service = new ConsultationRequestService(AppDataSource);

    // 获取客户端信息
    const ipAddress = c.req.header('x-forwarded-for') || c.req.header('x-real-ip') || 'unknown';
    const userAgent = c.req.header('user-agent') || 'unknown';

    // 创建客户需求
    const result = await service.create(data, ipAddress, userAgent);

    return c.json({
      success: true,
      message: '客户需求提交成功，我们将尽快与您联系',
      data: result
    }, 200);
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '提交失败';
    const statusCode = errorMessage.includes('频率过高') ? 429 : 400;

    return c.json({
      code: statusCode,
      message: errorMessage
    }, statusCode);
  }
});

export default app;