import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtStrategy } from './jwt.strategy';

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(private reflector: Reflector, private jwtStrategy: JwtStrategy) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const req = context.switchToHttp().getRequest();
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) return false;
    
    try {
      const user = await new Promise((resolve, reject) => {
        this.jwtStrategy.validate({ sub: 0, email: token }, (err, user) => {
          if (err) reject(err);
          resolve(user);
        });
      });
      req.user = user;
      return true;
    } catch (e) {
      return false;
    }
  }
}