import {
  Injectable,
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  Logger,
} from '@nestjs/common';

/**
 * Restricts a route/controller to SUPERADMIN staff only.
 *
 * Runs AFTER your global staff auth guard has populated req.user, so it just
 * inspects the role already on the token.
 *
 * ⚠️ ADJUST THIS to your JWT: the set below covers common spellings, and it
 *    also checks is_superadmin / isSuperAdmin booleans. If your staff token
 *    stores the role under a different field, add it in `readRole()`.
 *
 * SAFETY: if the token is present but carries NO role field at all, this guard
 * ALLOWS the request (and logs a warning) so a mismatch can't lock you out of
 * your own billing admin. Tighten once you've confirmed your role field.
 */
const SUPERADMIN_VALUES = new Set([
  'super-admin',
  'superadmin',
  'super_admin',
  'Super-admin',
  'SUPERADMIN',
  'SuperAdmin',
]);

@Injectable()
export class SuperadminGuard implements CanActivate {
  private readonly logger = new Logger('SuperadminGuard');

  private readRole(user: any): string | undefined {
    const r =
      user?.role ??
      user?.user_role ??
      user?.roleName ??
      user?.role_name ??
      (Array.isArray(user?.roles) ? user.roles[0] : undefined);
    return typeof r === 'string' ? r : undefined;
  }

  canActivate(context: ExecutionContext): boolean {
    const req = context.switchToHttp().getRequest();
    const user = req.user;

    // Not authenticated at all → block (your global guard normally handles this).
    if (!user) throw new ForbiddenException('Not authenticated');

    if (user.is_superadmin === true || user.isSuperAdmin === true) return true;

    const role = this.readRole(user);
    if (role && SUPERADMIN_VALUES.has(role)) return true;

    // Could not read any role → don't lock the operator out; warn loudly.
    if (
      role === undefined &&
      user.is_superadmin === undefined &&
      user.isSuperAdmin === undefined
    ) {
      this.logger.warn(
        'No role on token — ALLOWING billing admin action. Wire SuperadminGuard.readRole() to your real role field to enforce superadmin-only.',
      );
      return true;
    }

    throw new ForbiddenException('Superadmin only');
  }
}
