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

const userService = new UserService(AppDataSource);

const DeleteParams = z.object({
  id: z.coerce.number().openapi({
    param: { name: 'id', in: 'path' },
    example: 1,
    description: '用户ID'
  })
});

const routeDef = createRoute({
  method: 'delete',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: DeleteParams
  },
  responses: {
    204: { 
      description: '用户删除成功' 
    },
    404: {
      description: '用户不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  try {
    const { id } = c.req.valid('param');
    await userService.deleteUser(id);
    return c.body(null, 204);
  } catch (error) {
    return c.json({ 
      code: 500, 
      message: error instanceof Error ? error.message : '删除用户失败' 
    }, 500);
  }
});

export default app;