import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { UserService } from '../services/user.service';
import { AppDataSource, ErrorSchema } from '@d8d/shared-utils';
import { CreateUserDto, UpdateUserDto, UserSchema } from '../schemas/user.schema';
import { parseWithAwait } from '@d8d/shared-utils';
import { authMiddleware } from '@d8d/core-module/auth-module';
import { AuthContext } from '@d8d/shared-types';

// 创建用户路由 - 自定义业务逻辑（密码加密等）
const createUserRoute = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreateUserDto }
      }
    }
  },
  responses: {
    201: {
      description: '用户创建成功',
      content: {
        'application/json': { schema: UserSchema }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '创建用户失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 更新用户路由 - 自定义业务逻辑
const updateUserRoute = createRoute({
  method: 'put',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '用户ID'
      })
    }),
    body: {
      content: {
        'application/json': { schema: UpdateUserDto }
      }
    }
  },
  responses: {
    200: {
      description: '用户更新成功',
      content: {
        'application/json': { schema: UserSchema }
      }
    },
    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 deleteUserRoute = createRoute({
  method: 'delete',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '用户ID'
      })
    })
  },
  responses: {
    204: { description: '用户删除成功' },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '用户不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '删除用户失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  .openapi(createUserRoute, async (c) => {
    try {
      const data = c.req.valid('json');
      const userService = new UserService(AppDataSource);

      const result = await userService.createUser(data);

      return c.json(await parseWithAwait(UserSchema, result), 201);
    } 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(updateUserRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const data = c.req.valid('json');
      const userService = new UserService(AppDataSource);

      const result = await userService.updateUser(id, data);

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

      return c.json(await parseWithAwait(UserSchema, result), 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(deleteUserRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const userService = new UserService(AppDataSource);

      const success = await userService.deleteUser(id);

      if (!success) {
        return c.json({ code: 404, message: '资源不存在' }, 404);
      }

      return c.body(null, 204);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '删除用户失败'
      }, 500);
    }
  });

export default app;