import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { DataSource } from "typeorm";

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly connection: DataSource) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    try {
      const request = context.switchToHttp().getRequest();
      const tokenFromHeader = request.headers["authorization"];
      const api_key = request.headers["api-key"];

      if (!tokenFromHeader || !api_key) {
        return false;
      }
      const [getToken] = await this.connection.query(
        `SELECT token FROM phr_jwt_token WHERE token = ? and expiry >= now()`,
        [tokenFromHeader]
      );
      if (!getToken) {
        return false;
      }

      const accToken = await getToken.token;

      if (tokenFromHeader === accToken && api_key == process.env.API_KEY) {
        return true;
      } else {
        return false;
      }
    } catch (error) {
      console.error("Error in AuthGuard:", error);
      return false;
    }
  }
}
