import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, Inject, Logger } from '@nestjs/common';
import { Request } from 'express';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class SuperAdminAuthGuard implements CanActivate {
  private readonly logger = new Logger(SuperAdminAuthGuard.name);

  constructor(
    @Inject(ConfigService)
    private readonly configService: ConfigService,
  ) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<Request>();

    try {
      const credentials = this.extractBasicAuthCredentials(request);
      if (!credentials) {
        throw new UnauthorizedException('Basic authentication required');
      }

      const { username, password } = credentials;
      const expectedUsername = this.configService.get<string>('SUPER_ADMIN_USERNAME') ?? 'danak@dsc.com';
      const expectedPassword = this.configService.get<string>('SUPER_ADMIN_PASSWORD') ?? 'DsCdAnAk?@ABC';
      if (username !== expectedUsername || password !== expectedPassword) {
        this.logger.warn(`Invalid super admin credentials attempt for username: ${username}`);
        throw new UnauthorizedException('Invalid credentials');
      }

      return true;
    } catch (err) {
      if (err instanceof UnauthorizedException) {
        throw err;
      }
      this.logger.error('error in SuperAdminAuthGuard', err);
      throw new UnauthorizedException('Authentication failed');
    }
  }

  private extractBasicAuthCredentials(request: Request): { username: string; password: string } | null {
    const authHeader = request.headers.authorization;
    if (!authHeader) {
      return null;
    }

    const [type, encoded] = authHeader.split(' ');
    if (type?.toLowerCase() !== 'basic' || !encoded) {
      return null;
    }

    try {
      const decoded = Buffer.from(encoded, 'base64').toString('utf-8');
      const [username, password] = decoded.split(':');

      if (!username || !password) {
        return null;
      }

      return { username, password };
    } catch (error) {
      this.logger.error('Failed to decode Basic Auth credentials', error);
      return null;
    }
  }
}
