import { Context, Next } from 'hono';
import { JWTUtil } from '@d8d/shared-utils';

export async function tenantAuthMiddleware(c: Context, 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);
    }

    // 使用共享JWT工具验证token
    const payload = JWTUtil.verifyToken(token);

    // 检查是否为超级管理员（ID为1的用户）
    if (payload.id !== 1) {
      return c.json({ message: 'Access denied. Super admin privileges required' }, 403);
    }

    // 设置超级管理员上下文
    c.set('superAdminId', payload.id);
    await next();
  } catch (error) {
    console.error('Tenant auth middleware error:', error);
    return c.json({ message: 'Invalid token or authentication failed' }, 401);
  }
}