import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { timingSafeEqual } from "node:crypto";
import type { Request } from "express";

@Injectable()
export class AdminGuard implements CanActivate {
  constructor(private readonly config: ConfigService) {}

  canActivate(context: ExecutionContext): boolean {
    const req = context.switchToHttp().getRequest<Request>();
    const auth = req.header("authorization");
    if (!auth || !auth.startsWith("Bearer ")) {
      throw new UnauthorizedException("Missing admin token");
    }
    const token = auth.slice(7).trim();
    const expected = this.config.get<string>("ADMIN_API_TOKEN");
    if (!expected) {
      throw new UnauthorizedException("Admin auth not configured");
    }
    const a = Buffer.from(token);
    const b = Buffer.from(expected);
    if (a.length !== b.length || !timingSafeEqual(a, b)) {
      throw new UnauthorizedException("Invalid admin token");
    }
    req.auth = { kind: "admin" };
    return true;
  }
}
