import { Context, Next } from 'hono';
import { AuthService } from '../services/index.mt';
import { UserServiceMt } from '@d8d/user-module-mt';
import { AppDataSource } from '@d8d/shared-utils';
import { AuthContext } from '@d8d/shared-types';
import { parseWithAwait } from '@d8d/shared-utils';
import { UserSchemaMt } from '@d8d/user-module-mt';

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 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 UserServiceMt(AppDataSource);
    const authService = new AuthService(userService);
    const decoded = authService.verifyToken(token);

    // 从token中提取租户ID（如果存在）
    const tenantId = decoded.tenantId;
    const user = await userService.getUserById(decoded.id, tenantId);

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

    // 设置用户上下文
    const userData = await parseWithAwait(UserSchemaMt, user);
    c.set('user', userData);
    c.set('token', token);

    // 设置租户上下文（从用户信息中提取租户ID）
    if (user.tenantId) {
      c.set('tenantId', user.tenantId);
    }

    await next();
  } catch (error) {
    console.error('Authentication error:', error);
    return c.json({ message: 'Invalid token' }, 401);
  }
}