import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
import { JwtService } from "./jwt.service";

export interface RequestUser {
  userId: number;
}

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly jwt: JwtService) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const header = request.headers?.authorization as string | undefined;
    if (!header?.startsWith("Bearer ")) {
      throw new UnauthorizedException("missing bearer token");
    }
    const claims = this.jwt.verify(header.slice("Bearer ".length));
    const userId = Number(claims.sub);
    if (!Number.isInteger(userId) || userId <= 0) {
      throw new UnauthorizedException("invalid access token subject");
    }
    (request as { user?: RequestUser }).user = { userId };
    return true;
  }
}
