import { Injectable } from "@nestjs/common";
import { ThrottlerGuard } from "@nestjs/throttler";
import { createHash } from "crypto";
import type { Request } from "express";

@Injectable()
export class AuthThrottleGuard extends ThrottlerGuard {
  protected override async getTracker(req: Request): Promise<string> {
    // Track by IP address + User Agent for better security on sensitive auth operations
    const forwarded = req.headers["x-forwarded-for"];
    const forwardedIp = Array.isArray(forwarded) ? forwarded[0] : forwarded;
    const ip =
      (typeof forwardedIp === "string" ? forwardedIp.split(",")[0]?.trim() : undefined) ||
      (req.headers["x-real-ip"] as string | undefined) ||
      req.socket?.remoteAddress ||
      req.ip ||
      "unknown";

    const userAgent = req.headers["user-agent"] || "unknown";
    const userAgentHash = createHash("sha256").update(userAgent).digest("hex").slice(0, 16);

    const normalizedIp = ip.replace(/^::ffff:/, "");

    const resolvedIp = await Promise.resolve(normalizedIp);
    return `auth_${resolvedIp}_${userAgentHash}`;
  }
}
