import {
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  Injectable,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { MODULES_KEY } from '../decorators/modules-guard.decorators';
import { Modules } from '.prisma/client';



interface RequestWithUser extends Request {
  // TODO: Create an actual user model based on OAuth signin
  user: any;
}

@Injectable()
export class ModulesGuard implements CanActivate {
  constructor(private reflector: Reflector) { }
  canActivate(ctx: ExecutionContext): boolean {
    const requiredModules = this.reflector.getAllAndOverride<Modules[]>(
      MODULES_KEY,
      [ctx.getHandler(), ctx.getClass()],
    );
    //for "deny-by-default" when role is wrong or unavailable
    if (!requiredModules || requiredModules.length === 0) {
      return true;
    }
    const request = ctx.switchToHttp().getRequest<RequestWithUser>();
    const user = request.user;

    if (!user) {
      return false;
    }
    for (const module of requiredModules) {
        if (!user.user_module_access.includes(module)) {
          throw new ForbiddenException(
            `This account does not have required access to: ${module}. current user modules: ${user.user_module_access} , required modules: ${requiredModules}`,
          );
        }
    }
    return true;
  }
}
