import { Context, Next } from 'hono';
import { AuthService } from '../modules/auth/auth.service';
import { UserService } from '../modules/users/user.service';
import { AppDataSource } from '../data-source';
import { AuthContext } from '../types/context';
import { DisabledStatus, DeleteStatus } from '@/share/types';
import { immediateTraineeExpiryMiddleware } from './trainee-expiry.middleware';

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

    const token = authHeader.split(' ')[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.getUserById(decoded.id);
    
    if (!user) {
      return c.json({ message: 'User not found' }, 401);
    }

    // 检查用户状态
    if (user.isDisabled === DisabledStatus.DISABLED) {
      return c.json({ message: 'User is disabled' }, 403);
    }

    if (user.isDeleted === DeleteStatus.DELETED) {
      return c.json({ message: 'User not found' }, 401);
    }

    c.set('user', user);
    c.set('token', token);
    
    // 在认证成功后立即检查学员过期状态
    await immediateTraineeExpiryMiddleware(c, next);
  } catch (error) {
    console.error('Authentication error:', error);
    return c.json({ message: 'Invalid token' }, 401);
  }
}