import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { UserService } from '@d8d/core-module/user-module';
import { ErrorSchema } from '@d8d/shared-utils';
import { AppDataSource } from '@d8d/shared-utils';
import { AuthContext } from '@d8d/shared-types';
import { parseWithAwait } from '@d8d/shared-utils';
import { TalentMeResponseSchema } from '../../schemas/index';
import { talentAuthMiddleware } from '../../middleware/index';

const talentMeRoute = createRoute({
  method: 'get',
  path: '/me',
  security: [
    {
      Bearer: []
    }
  ],
  middleware: talentAuthMiddleware,
  responses: {
    200: {
      description: '获取人才用户信息成功',
      content: {
        'application/json': {
          schema: TalentMeResponseSchema
        }
      }
    },
    401: {
      description: '未授权或token无效',
      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(talentMeRoute, async (c) => {
  try {
    const user = c.get('user');
    if (!user) {
      return c.json({ code: 401, message: '未授权' }, 401);
    }

    const userService = new UserService(AppDataSource);

    // 获取包含残疾人详细信息的用户数据
    const userWithPerson = await userService.getUserWithDisabledPerson(user.id);

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

    // 构建符合Schema的响应对象
    const userResponse = {
      id: userWithPerson.id,
      username: userWithPerson.username,
      userType: userWithPerson.userType,
      personId: userWithPerson.personId,
      phone: userWithPerson.phone,
      nickname: userWithPerson.nickname,
      name: userWithPerson.name,
      avatarFileId: userWithPerson.avatarFileId,
      isDisabled: userWithPerson.isDisabled,
      createdAt: userWithPerson.createdAt,
      updatedAt: userWithPerson.updatedAt,
      // 将person关系映射为personInfo
      personInfo: userWithPerson.person || null
    };

    return c.json(await parseWithAwait(TalentMeResponseSchema, userResponse), 200);
  } catch (error) {
    return c.json(
      {
        code: 500,
        message: error instanceof Error ? error.message : '获取用户信息失败'
      },
      500
    );
  }
});

export default app;
