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

// 地点查询参数Schema
const searchLocationsSchema = z.object({
  provinceId: z.coerce.number().int().positive('省份ID必须为正整数').optional().openapi({
    example: 1,
    description: '省份ID'
  }),
  cityId: z.coerce.number().int().positive('城市ID必须为正整数').optional().openapi({
    example: 11,
    description: '城市ID'
  }),
  districtId: z.coerce.number().int().positive('区县ID必须为正整数').optional().openapi({
    example: 110105,
    description: '区县ID'
  }),
  keyword: z.string().max(50, '关键词长度不能超过50个字符').optional().openapi({
    example: '北京南站',
    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 locationResponseSchema = z.object({
  id: z.number(),
  name: z.string(),
  address: z.string(),
  province: z.string(),
  city: z.string(),
  district: z.string(),
  latitude: z.number(),
  longitude: z.number(),
  type: z.enum(['火车站', '汽车站', '机场', '景点', '酒店', '其他'])
});

// 地点搜索结果Schema
const locationSearchResultSchema = z.object({
  success: z.boolean(),
  data: z.object({
    locations: z.array(locationResponseSchema),
    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 searchLocationsRoute = createRoute({
  method: 'get',
  path: '/',
  request: {
    query: searchLocationsSchema
  },
  responses: {
    200: {
      description: '地点搜索成功',
      content: {
        'application/json': { schema: locationSearchResultSchema }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: errorSchema } }
    },
    500: {
      description: '搜索地点失败',
      content: { 'application/json': { schema: errorSchema } }
    }
  }
});

const app = new OpenAPIHono()
  .openapi(searchLocationsRoute, async (c) => {
    try {
      const { provinceId, cityId, districtId, keyword, page, pageSize } = c.req.valid('query');

      // 模拟地点数据
      const mockLocations: Array<{
        id: number;
        name: string;
        address: string;
        province: string;
        city: string;
        district: string;
        latitude: number;
        longitude: number;
        type: '火车站' | '汽车站' | '机场' | '景点' | '酒店' | '其他';
      }> = [
        {
          id: 1,
          name: '北京南站',
          address: '北京市丰台区北京南站',
          province: '北京市',
          city: '北京市',
          district: '丰台区',
          latitude: 39.865,
          longitude: 116.378,
          type: '火车站'
        },
        {
          id: 2,
          name: '上海虹桥站',
          address: '上海市闵行区虹桥站',
          province: '上海市',
          city: '上海市',
          district: '闵行区',
          latitude: 31.198,
          longitude: 121.319,
          type: '火车站'
        },
        {
          id: 3,
          name: '北京首都国际机场',
          address: '北京市顺义区首都机场',
          province: '北京市',
          city: '北京市',
          district: '顺义区',
          latitude: 40.079,
          longitude: 116.603,
          type: '机场'
        },
        {
          id: 4,
          name: '上海浦东国际机场',
          address: '上海市浦东新区浦东机场',
          province: '上海市',
          city: '上海市',
          district: '浦东新区',
          latitude: 31.144,
          longitude: 121.808,
          type: '机场'
        },
        {
          id: 5,
          name: '北京八达岭长城',
          address: '北京市延庆区八达岭长城',
          province: '北京市',
          city: '北京市',
          district: '延庆区',
          latitude: 40.356,
          longitude: 116.017,
          type: '景点'
        },
        {
          id: 6,
          name: '上海外滩',
          address: '上海市黄浦区外滩',
          province: '上海市',
          city: '上海市',
          district: '黄浦区',
          latitude: 31.239,
          longitude: 121.490,
          type: '景点'
        },
        {
          id: 7,
          name: '北京王府井',
          address: '北京市东城区王府井大街',
          province: '北京市',
          city: '北京市',
          district: '东城区',
          latitude: 39.908,
          longitude: 116.407,
          type: '其他'
        },
        {
          id: 8,
          name: '上海南京路步行街',
          address: '上海市黄浦区南京路',
          province: '上海市',
          city: '上海市',
          district: '黄浦区',
          latitude: 31.238,
          longitude: 121.475,
          type: '其他'
        }
      ];

      // 筛选逻辑
      let filteredLocations = mockLocations;

      if (provinceId) {
        // 根据省份ID筛选（这里简化处理，实际应该根据省份名称映射）
        const provinceMap: Record<number, string> = {
          1: '北京市',
          9: '上海市'
        };
        const provinceName = provinceMap[provinceId];
        if (provinceName) {
          filteredLocations = filteredLocations.filter(location => location.province === provinceName);
        }
      }

      if (cityId) {
        // 根据城市ID筛选
        const cityMap: Record<number, string> = {
          11: '北京市',
          31: '上海市'
        };
        const cityName = cityMap[cityId];
        if (cityName) {
          filteredLocations = filteredLocations.filter(location => location.city === cityName);
        }
      }

      if (districtId) {
        // 根据区县ID筛选
        const districtMap: Record<number, string> = {
          110105: '朝阳区',
          310101: '黄浦区'
        };
        const districtName = districtMap[districtId];
        if (districtName) {
          filteredLocations = filteredLocations.filter(location => location.district === districtName);
        }
      }

      if (keyword) {
        filteredLocations = filteredLocations.filter(location =>
          location.name.includes(keyword) || location.address.includes(keyword)
        );
      }

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

      return c.json({
        success: true,
        data: {
          locations: paginatedLocations,
          pagination: {
            page,
            pageSize,
            total: filteredLocations.length,
            totalPages: Math.ceil(filteredLocations.length / pageSize)
          }
        },
        message: '搜索地点成功'
      } as const, 200);
    } catch (error) {
      console.error('搜索地点失败:', error);
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '搜索地点失败'
      }, 500);
    }
  });

export default app;