import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { UserService } from '../../modules/users/user.service';
import { z } from '@hono/zod-openapi';
import { authMiddleware } from '../../middleware/auth.middleware';
import { ErrorSchema } from '../../utils/errorHandler';
import { AppDataSource } from '../../data-source';
import { AuthContext } from '../../types/context';
import { UserSchema } from '../../modules/users/user.schema';
import { parseWithAwait } from '@/server/utils/parseWithAwait';

const userService = new UserService(AppDataSource);

const PaginationQuery = z.object({
  page: z.coerce.number().int().positive().default(1).openapi({
    example: 1,
    description: '页码，从1开始'
  }),
  pageSize: z.coerce.number().int().positive().default(10).openapi({
    example: 10,
    description: '每页数量'
  }),
  keyword: z.string().optional().openapi({
    example: 'admin',
    description: '搜索关键词(用户名/昵称/手机号)'
  })
});

const UserListResponse = z.object({
  data: z.array(UserSchema),
  pagination: z.object({
    total: z.number().openapi({
      example: 100,
      description: '总记录数'
    }),
    current: z.number().openapi({
      example: 1,
      description: '当前页码'
    }),
    pageSize: z.number().openapi({
      example: 10,
      description: '每页数量'
    })
  })
});

const listUsersRoute = createRoute({
  method: 'get',
  path: '/',
  middleware: [authMiddleware],
  request: {
    query: PaginationQuery
  },
  responses: {
    200: {
      description: '成功获取用户列表',
      content: {
        'application/json': {
          schema: UserListResponse
        }
      }
    },
    400: {
      description: '参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '获取用户列表失败',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono<AuthContext>().openapi(listUsersRoute, async (c) => {
  try {
    const { page, pageSize, keyword } = c.req.valid('query');
    const [users, total] = await userService.getUsersWithPagination({
      page,
      pageSize,
      keyword
    });
    
    return c.json({
      data: await parseWithAwait(z.array(UserSchema), users),
      pagination: {
        total,
        current: page,
        pageSize
      }
    }, 200);
  } catch (error) {
    if (error instanceof z.ZodError) {
      return c.json({ code: 400, message: '参数错误' }, 400);
    }
    return c.json({
      code: 500,
      message: error instanceof Error ? error.message : '获取用户列表失败'
    }, 500);
  }
});

export default app;