import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common';
import * as admin from 'firebase-admin';

@Injectable()
export class OptionalAuthGuard implements CanActivate {
  constructor(@Inject('FIREBASE_ADMIN') private firebaseAdmin: admin.app.App) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const authHeader = request.headers.authorization;

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      //throw new UnauthorizedException('Missing or invalid authorization token');
      return true;
    }

    const token = authHeader.split('Bearer ')[1];

    try {
      const decodedToken = await this.firebaseAdmin.auth().verifyIdToken(token);

      // Check if email is verified (optional but recommended)
      if (!decodedToken.email_verified) {
        //throw new UnauthorizedException('Email not verified');
        return true;
      }

      // Add the user to the request
      request.user = {
        uid: decodedToken.uid,
        email: decodedToken.email,
        role: decodedToken.role || null,
        // Add other user info as needed
      };

      return true;
    } catch (error) {
      //throw new UnauthorizedException('Invalid token');
      return true;
    }
  }
}
// import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common';
// import * as admin from 'firebase-admin';

// @Injectable()
// export class OptionalAuthGuard implements CanActivate {
//   constructor(
//     @Inject('FIREBASE_ADMIN')
//     private readonly firebaseAdmin: typeof admin,
//   ) {}

//   async canActivate(context: ExecutionContext): Promise<boolean> {
//     const request = context.switchToHttp().getRequest<Request>();
//     const token = this.extractTokenFromHeader(request);

//     if (!token) {
//       return true;
//     }

//     try {
//       const decodedToken = await this.firebaseAdmin.auth().verifyIdToken(token);
//       request['user'] = decodedToken;
//       return true;
//     } catch (error) {
//       //throw new UnauthorizedException('Invalid token');
//       request['user'] = null;
//       return true;
//     }
//   }

//   private extractTokenFromHeader(request: Request): string | undefined {
//     const [type, token] = request.headers['authorization']?.split(' ') ?? [];
//     return type === 'Bearer' ? token : undefined;
//   }
// }
