import { Context, Next } from 'hono';
import { AuthService } from '../services/index';
import { UserService } from '../../../user-module/src/services/index';
import { AppDataSource } from '@d8d/shared-utils';
import { AuthContext, UserType } from '@d8d/shared-types';
import { parseWithAwait } from '@d8d/shared-utils';
import { TalentUserResponseSchema } from '../schemas/index';

export async function talentAuthMiddleware(c: Context<AuthContext>, next: Next) {
  try {
    const authHeader = c.req.header('Authorization');
    if (!authHeader) {
      return c.json({ message: 'Authorization header missing' }, 401);
    }

    const tokenParts = authHeader.split(' ');
    if (tokenParts.length !== 2 || tokenParts[0] !== 'Bearer') {
      return c.json({ message: 'Authorization header missing' }, 401);
    }

    const token = tokenParts[1];
    if (!token) {
      return c.json({ message: 'Token missing' }, 401);
    }

    const userService = new UserService(AppDataSource);
    const authService = new AuthService(userService);
    const decoded = authService.verifyToken(token);

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

    if (!user) {
      return c.json({ message: 'User not found' }, 401);
    }

    // 验证用户是否是人才用户
    if (user.userType !== UserType.TALENT) {
      return c.json({ message: 'User is not a talent user' }, 403);
    }

    // 设置用户上下文（包含残疾人详情）
    const userData = {
      id: user.id,
      username: user.username,
      userType: user.userType,
      personId: user.personId,
      phone: user.phone,
      nickname: user.nickname,
      name: user.name,
      avatarFileId: user.avatarFileId,
      isDisabled: user.isDisabled,
      createdAt: user.createdAt,
      updatedAt: user.updatedAt,
      // 将person关系映射为personInfo
      personInfo: user.person || null
    };

    c.set('user', userData);
    c.set('token', token);

    await next();
  } catch (error) {
    console.error('Talent authentication error:', error);
    return c.json({ message: 'Invalid token or insufficient permissions' }, 401);
  }
}
