import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';

// 路线搜索参数Schema
const searchRoutesSchema = z.object({
  startLocationId: z.coerce.number().int().positive('出发地ID必须为正整数').optional().openapi({
    example: 1,
    description: '出发地ID'
  }),
  endLocationId: z.coerce.number().int().positive('目的地ID必须为正整数').optional().openapi({
    example: 2,
    description: '目的地ID'
  }),
  date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, '日期格式必须为YYYY-MM-DD').optional().openapi({
    example: '2025-10-18',
    description: '出发日期'
  }),
  routeType: z.enum(['去程', '返程']).optional().openapi({
    example: '去程',
    description: '路线类型'
  }),
  minPrice: z.coerce.number().int().min(0, '最低价格不能为负数').optional().openapi({
    example: 100,
    description: '最低价格'
  }),
  maxPrice: z.coerce.number().int().min(0, '最高价格不能为负数').optional().openapi({
    example: 500,
    description: '最高价格'
  }),
  sortBy: z.enum(['price', 'departureTime']).default('departureTime').openapi({
    example: 'departureTime',
    description: '排序字段'
  }),
  sortOrder: z.enum(['ASC', 'DESC']).default('ASC').openapi({
    example: 'ASC',
    description: '排序方向'
  }),
  page: z.coerce.number().int().min(1).default(1).openapi({
    example: 1,
    description: '页码'
  }),
  pageSize: z.coerce.number().int().min(1).max(50).default(20).openapi({
    example: 20,
    description: '每页数量'
  }),
});

// 路线搜索结果Schema
const routeSearchResultSchema = z.object({
  success: z.boolean(),
  data: z.object({
    routes: z.array(z.object({
      id: z.number(),
      startLocation: z.object({
        id: z.number(),
        name: z.string(),
        address: z.string()
      }),
      endLocation: z.object({
        id: z.number(),
        name: z.string(),
        address: z.string()
      }),
      departureTime: z.string(),
      vehicleType: z.string(),
      price: z.number(),
      seatCount: z.number(),
      routeType: z.string(),
      activity: z.object({
        id: z.number(),
        name: z.string(),
        description: z.string(),
        venueLocation: z.object({
          id: z.number(),
          name: z.string(),
          address: z.string()
        }),
        startDate: z.string(),
        endDate: z.string()
      })
    })),
    activities: z.array(z.object({
      id: z.number(),
      name: z.string(),
      description: z.string(),
      venueLocation: z.object({
        id: z.number(),
        name: z.string(),
        address: z.string()
      }),
      startDate: z.string(),
      endDate: z.string()
    })),
    pagination: z.object({
      page: z.number(),
      pageSize: z.number(),
      total: z.number(),
      totalPages: z.number()
    })
  }),
  message: z.string()
});

// 错误响应Schema
const errorSchema = z.object({
  code: z.number(),
  message: z.string(),
  errors: z.array(z.object({
    path: z.array(z.string()),
    message: z.string()
  })).optional()
});

// 创建路线搜索路由
const searchRoutesRoute = createRoute({
  method: 'get',
  path: '/search',
  request: {
    query: searchRoutesSchema
  },
  responses: {
    200: {
      description: '路线搜索成功',
      content: {
        'application/json': { schema: routeSearchResultSchema }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: errorSchema } }
    },
    500: {
      description: '搜索路线失败',
      content: { 'application/json': { schema: errorSchema } }
    }
  }
});

const app = new OpenAPIHono()
  .openapi(searchRoutesRoute, async (c) => {
    try {
      const {
        startLocationId,
        endLocationId,
        routeType,
        minPrice,
        maxPrice,
        sortBy,
        sortOrder,
        page,
        pageSize
      } = c.req.valid('query');

      // 这里需要调用路线服务进行查询
      // 由于路线服务尚未实现，这里返回模拟数据
      const mockRoutes = [
        {
          id: 1,
          startLocation: { id: 1, name: '北京南站', address: '北京市丰台区北京南站' },
          endLocation: { id: 2, name: '上海虹桥站', address: '上海市闵行区虹桥站' },
          departureTime: '2025-10-18T08:00:00Z',
          vehicleType: '大巴',
          price: 200,
          seatCount: 40,
          routeType: '去程',
          activity: {
            id: 1,
            name: '北京到上海商务会议',
            description: '前往上海参加商务会议',
            venueLocation: { id: 2, name: '上海虹桥站', address: '上海市闵行区虹桥站' },
            startDate: '2025-10-18T09:00:00Z',
            endDate: '2025-10-20T18:00:00Z'
          }
        },
        {
          id: 2,
          startLocation: { id: 2, name: '上海虹桥站', address: '上海市闵行区虹桥站' },
          endLocation: { id: 1, name: '北京南站', address: '北京市丰台区北京南站' },
          departureTime: '2025-10-20T18:00:00Z',
          vehicleType: '大巴',
          price: 200,
          seatCount: 40,
          routeType: '返程',
          activity: {
            id: 1,
            name: '北京到上海商务会议',
            description: '前往上海参加商务会议',
            venueLocation: { id: 2, name: '上海虹桥站', address: '上海市闵行区虹桥站' },
            startDate: '2025-10-18T09:00:00Z',
            endDate: '2025-10-20T18:00:00Z'
          }
        }
      ];

      // 简单的筛选逻辑（在实际实现中应该在数据库层面进行）
      let filteredRoutes = mockRoutes;

      if (startLocationId) {
        filteredRoutes = filteredRoutes.filter(route => route.startLocation.id === startLocationId);
      }

      if (endLocationId) {
        filteredRoutes = filteredRoutes.filter(route => route.endLocation.id === endLocationId);
      }

      if (routeType) {
        filteredRoutes = filteredRoutes.filter(route => route.routeType === routeType);
      }

      if (minPrice !== undefined) {
        filteredRoutes = filteredRoutes.filter(route => route.price >= minPrice);
      }

      if (maxPrice !== undefined) {
        filteredRoutes = filteredRoutes.filter(route => route.price <= maxPrice);
      }

      // 排序
      filteredRoutes.sort((a, b) => {
        if (sortBy === 'price') {
          return sortOrder === 'ASC' ? a.price - b.price : b.price - a.price;
        } else {
          return sortOrder === 'ASC'
            ? new Date(a.departureTime).getTime() - new Date(b.departureTime).getTime()
            : new Date(b.departureTime).getTime() - new Date(a.departureTime).getTime();
        }
      });

      // 分页
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      const paginatedRoutes = filteredRoutes.slice(startIndex, endIndex);

      // 去重后的活动列表
      const uniqueActivities = Array.from(
        new Map(paginatedRoutes.map(route => [route.activity.id, route.activity])).values()
      );

      return c.json({
        success: true,
        data: {
          routes: paginatedRoutes,
          activities: uniqueActivities,
          pagination: {
            page,
            pageSize,
            total: filteredRoutes.length,
            totalPages: Math.ceil(filteredRoutes.length / pageSize)
          }
        },
        message: '搜索路线成功'
      }, 200);
    } catch (error) {
      console.error('搜索路线失败:', error);
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '搜索路线失败'
      }, 500);
    }
  });

export default app;