import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { AppDataSource, ErrorSchema, parseWithAwait } from '@d8d/shared-utils';
import { authMiddleware } from '@d8d/auth-module';
import { AuthContext } from '@d8d/shared-types';
import { PlatformService } from '../services/platform.service';
import {
  PlatformSchema,
  CreatePlatformSchema,
  UpdatePlatformSchema,
  DeletePlatformSchema,
  PaginationQuerySchema,
  SearchPlatformQuerySchema
} from '../schemas/platform.schema';

// 创建平台路由 - 返回布尔值
const createPlatformRoute = createRoute({
  method: 'post',
  path: '/createPlatform',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreatePlatformSchema }
      }
    }
  },
  responses: {
    200: {
      description: '平台创建成功',
      content: {
        'application/json': { schema: PlatformSchema }
      }
    },
    400: {
      description: '参数错误或平台名称已存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '创建平台失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 删除平台路由 - 返回布尔值
const deletePlatformRoute = createRoute({
  method: 'post',
  path: '/deletePlatform',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: DeletePlatformSchema }
      }
    }
  },
  responses: {
    200: {
      description: '平台删除成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean().openapi({ description: '是否成功' })
          })
        }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '删除平台失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 更新平台路由 - 返回布尔值
const updatePlatformRoute = createRoute({
  method: 'post',
  path: '/updatePlatform',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: UpdatePlatformSchema }
      }
    }
  },
  responses: {
    200: {
      description: '平台更新成功',
      content: {
        'application/json': { schema: PlatformSchema }
      }
    },
    400: {
      description: '参数错误或平台名称已存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '平台不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '更新平台失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 获取所有平台路由 - 分页查询
const getAllPlatformsRoute = createRoute({
  method: 'get',
  path: '/getAllPlatforms',
  middleware: [authMiddleware],
  request: {
    query: PaginationQuerySchema
  },
  responses: {
    200: {
      description: '获取平台列表成功',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(PlatformSchema).openapi({ description: '平台列表' }),
            total: z.number().int().openapi({ description: '总记录数' })
          })
        }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取平台列表失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 搜索平台路由 - 按名称模糊搜索
const searchPlatformsRoute = createRoute({
  method: 'get',
  path: '/searchPlatforms',
  middleware: [authMiddleware],
  request: {
    query: SearchPlatformQuerySchema
  },
  responses: {
    200: {
      description: '搜索平台成功',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(PlatformSchema).openapi({ description: '平台列表' }),
            total: z.number().int().openapi({ description: '总记录数' })
          })
        }
      }
    },
    400: {
      description: '搜索关键词不能为空',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '搜索平台失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 获取单个平台路由
const getPlatformRoute = createRoute({
  method: 'get',
  path: '/getPlatform/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().int().positive().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '平台ID'
      })
    })
  },
  responses: {
    200: {
      description: '获取平台详情成功',
      content: {
        'application/json': { schema: PlatformSchema.nullable() }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取平台详情失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  // 创建平台
  .openapi(createPlatformRoute, async (c) => {
    try {
      const data = c.req.valid('json');
      const platformService = new PlatformService(AppDataSource);

      const result = await platformService.create(data);

      return c.json(await parseWithAwait(PlatformSchema, result), 200);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return c.json({
          code: 400,
          message: '参数错误',
          errors: error.issues
        }, 400);
      }

      // 处理平台名称重复错误
      if (error instanceof Error && error.message.includes('平台名称已存在')) {
        return c.json({
          code: 400,
          message: '平台名称已存在'
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '创建平台失败'
      }, 500);
    }
  })
  // 删除平台
  .openapi(deletePlatformRoute, async (c) => {
    try {
      const { id } = c.req.valid('json');
      const platformService = new PlatformService(AppDataSource);

      const success = await platformService.delete(id);

      return c.json({ success }, 200);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return c.json({
          code: 400,
          message: '参数错误',
          errors: error.issues
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '删除平台失败'
      }, 500);
    }
  })
  // 更新平台
  .openapi(updatePlatformRoute, async (c) => {
    try {
      const data = c.req.valid('json');
      const platformService = new PlatformService(AppDataSource);

      const result = await platformService.update(data.id, data);

      if (!result) {
        return c.json({ code: 404, message: '平台不存在' }, 404);
      }

      return c.json(await parseWithAwait(PlatformSchema, result), 200);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return c.json({
          code: 400,
          message: '参数错误',
          errors: error.issues
        }, 400);
      }

      // 处理平台名称重复错误
      if (error instanceof Error && error.message.includes('平台名称已存在')) {
        return c.json({
          code: 400,
          message: '平台名称已存在'
        }, 400);
      }

      // 处理平台不存在错误
      if (error instanceof Error && error.message.includes('平台不存在')) {
        return c.json({
          code: 404,
          message: '平台不存在'
        }, 404);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '更新平台失败'
      }, 500);
    }
  })
  // 获取所有平台
  .openapi(getAllPlatformsRoute, async (c) => {
    try {
      const { skip, take } = c.req.valid('query');
      const platformService = new PlatformService(AppDataSource);

      const result = await platformService.findAll(skip, take);

      return c.json(result, 200);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取平台列表失败'
      }, 500);
    }
  })
  // 搜索平台
  .openapi(searchPlatformsRoute, async (c) => {
    try {
      const { name, skip, take } = c.req.valid('query');
      const platformService = new PlatformService(AppDataSource);

      const result = await platformService.searchByName(name, skip, take);

      return c.json(result, 200);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '搜索平台失败'
      }, 500);
    }
  })
  // 获取单个平台
  .openapi(getPlatformRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const platformService = new PlatformService(AppDataSource);

      const result = await platformService.findOne(id);

      if (!result) {
        return c.json(null, 200);
      }

      const validatedResult = await parseWithAwait(PlatformSchema, result);
      return c.json(validatedResult, 200);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取平台详情失败'
      }, 500);
    }
  });

export default app;