import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { ErrorSchema } from '@d8d/shared-utils';
import { authMiddleware } from '../middleware/index.mt';
import { AuthContext } from '@d8d/shared-types';
import { UserSchema, UpdateUserDto } from '@d8d/user-module';
import { UserServiceMt } from '@d8d/user-module-mt';
import { AppDataSource } from '@d8d/shared-utils';
import { parseWithAwait } from '@d8d/shared-utils';
import { UserResponseSchema } from '../schemas/index.mt';

const routeDef = createRoute({
  method: 'put',
  path: '/me',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': {
          schema: UpdateUserDto
        }
      }
    }
  },
  responses: {
    200: {
      description: '用户信息更新成功',
      content: {
        'application/json': {
          schema: UserResponseSchema
        }
      }
    },
    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 app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  try {
    const user = c.get('user');
    const updateData = c.req.valid('json');

    const userService = new UserServiceMt(AppDataSource);

    // 更新用户信息
    const updatedUser = await userService.updateUser(user.id, updateData);

    if (!updatedUser) {
      return c.json({ code: 404, message: '用户不存在' }, 404);
    }

    // 返回更新后的用户信息（不包含密码）
    return c.json(await parseWithAwait(UserResponseSchema, updatedUser), 200);

  } catch (error) {
    console.error('更新用户信息失败:', error);
    return c.json({
      code: 500,
      message: error instanceof Error ? error.message : '更新用户信息失败'
    }, 500);
  }
});

export default app;