import { Context, Next } from 'hono';
import { UserEntity as User } from '../modules/users/user.entity';

type PermissionCheck = (user: User) => boolean | Promise<boolean>;

export function checkPermission(requiredRoles: string[]): PermissionCheck {
  return (user: User) => {
    if (!user.roles) return false;
    return user.roles.some(role => requiredRoles.includes(role.name));
  };
}

export function permissionMiddleware(check: PermissionCheck) {
  return async (c: Context, next: Next) => {
    try {
      const user = c.get('user') as User | undefined;
      if (!user) {
        return c.json({ message: 'Unauthorized' }, 401);
      }

      const hasPermission = await check(user);
      if (!hasPermission) {
        return c.json({ message: 'Forbidden' }, 403);
      }

      await next();
    } catch (error) {
      console.error('Permission check error:', error);
      return c.json({ message: 'Internal server error' }, 500);
    }
  };
}

// 示例用法：
// app.get('/admin', 
//   authMiddleware,
//   permissionMiddleware(checkPermission(['admin'])),
//   (c) => {...}
// )