import { beforeEach, describe, expect, test, vi } from "vitest";
import { logger } from "@formbricks/logger";
import { err, ok } from "@formbricks/types/error-handlers";
import { hashString } from "@/lib/hash-string";
// Import modules after mocking
import { getClientIpFromHeaders } from "@/lib/utils/client-ip";
import {
  applyClientRateLimit,
  applyIPRateLimit,
  applyRateLimit,
  assertRateLimitAvailable,
  getClientIdentifier,
  reserveRateLimitUsage,
  settleRateLimitUsage,
} from "./helpers";
import { checkRateLimit, peekRateLimit, reserveRateLimit, settleRateLimit } from "./rate-limit";
import { rateLimitConfigs } from "./rate-limit-configs";

// Mock all dependencies
vi.mock("@/lib/utils/client-ip", () => ({
  UNTRUSTED_CLIENT_IP: "untrusted-client-ip",
  getClientIpFromHeaders: vi.fn(),
}));

vi.mock("@/lib/hash-string", () => ({
  hashString: vi.fn(),
}));

vi.mock("./rate-limit", () => ({
  checkRateLimit: vi.fn(),
  peekRateLimit: vi.fn(),
  reserveRateLimit: vi.fn(),
  settleRateLimit: vi.fn(),
}));

vi.mock("@formbricks/logger", () => ({
  logger: {
    error: vi.fn(),
  },
}));

describe("helpers", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  describe("getClientIdentifier", () => {
    test("should get client IP and return hashed identifier", async () => {
      const mockIp = "192.168.1.1";
      const mockHashedIp = "abc123hashedip";

      vi.mocked(getClientIpFromHeaders).mockResolvedValue(mockIp);
      vi.mocked(hashString).mockReturnValue(mockHashedIp);

      const result = await getClientIdentifier();

      expect(getClientIpFromHeaders).toHaveBeenCalledOnce();
      expect(hashString).toHaveBeenCalledWith(mockIp);
      expect(result).toBe(mockHashedIp);

      // Verify no error was logged on successful hashing
      expect(logger.error).not.toHaveBeenCalled();
    });

    test("should handle IP retrieval errors", async () => {
      const mockError = new Error("Failed to get IP");
      vi.mocked(getClientIpFromHeaders).mockRejectedValue(mockError);

      await expect(getClientIdentifier()).rejects.toThrow("Failed to get IP");
    });

    test("should handle hashing errors with proper logging", async () => {
      const mockIp = "192.168.1.1";
      const originalError = new Error("Hashing failed");

      vi.mocked(getClientIpFromHeaders).mockResolvedValue(mockIp);
      vi.mocked(hashString).mockImplementation(() => {
        throw originalError;
      });

      await expect(getClientIdentifier()).rejects.toThrow("Failed to hash IP");

      // Verify that the error was logged with proper context (pino 10 format: object first, message second)
      expect(logger.error).toHaveBeenCalledWith({ error: originalError }, "Failed to hash IP");
    });
  });

  describe("applyRateLimit", () => {
    const mockConfig = {
      interval: 300,
      allowedPerInterval: 5,
      namespace: "test",
    };

    const mockIdentifier = "test-identifier";

    test("should allow request when rate limit check passes", async () => {
      vi.mocked(checkRateLimit).mockResolvedValue(ok({ allowed: true }));

      await expect(applyRateLimit(mockConfig, mockIdentifier)).resolves.toEqual({ allowed: true });

      expect(checkRateLimit).toHaveBeenCalledWith(mockConfig, mockIdentifier);
    });

    test("should throw error when rate limit is exceeded", async () => {
      vi.mocked(checkRateLimit).mockResolvedValue(ok({ allowed: false }));

      await expect(applyRateLimit(mockConfig, mockIdentifier)).rejects.toThrow(
        "Maximum number of requests reached. Please try again later."
      );

      expect(checkRateLimit).toHaveBeenCalledWith(mockConfig, mockIdentifier);
    });

    test("should throw error when rate limit check fails", async () => {
      vi.mocked(checkRateLimit).mockResolvedValue(err("Redis connection failed"));

      await expect(applyRateLimit(mockConfig, mockIdentifier)).rejects.toThrow(
        "Maximum number of requests reached. Please try again later."
      );

      expect(checkRateLimit).toHaveBeenCalledWith(mockConfig, mockIdentifier);
    });

    test("should throw error when rate limit check throws exception", async () => {
      const mockError = new Error("Unexpected error");
      vi.mocked(checkRateLimit).mockRejectedValue(mockError);

      await expect(applyRateLimit(mockConfig, mockIdentifier)).rejects.toThrow("Unexpected error");

      expect(checkRateLimit).toHaveBeenCalledWith(mockConfig, mockIdentifier);
    });

    test("should work with different configurations", async () => {
      const customConfig = {
        interval: 3600,
        allowedPerInterval: 100,
        namespace: "api:v1",
      };

      vi.mocked(checkRateLimit).mockResolvedValue(ok({ allowed: true }));

      await expect(applyRateLimit(customConfig, "api-key-identifier")).resolves.toEqual({ allowed: true });

      expect(checkRateLimit).toHaveBeenCalledWith(customConfig, "api-key-identifier");
    });

    test("should work with different identifiers", async () => {
      vi.mocked(checkRateLimit).mockResolvedValue(ok({ allowed: true }));

      const identifiers = ["user-123", "ip-192.168.1.1", "auth-login-hashedip", "api-key-abc123"];

      for (const identifier of identifiers) {
        await expect(applyRateLimit(mockConfig, identifier)).resolves.toEqual({ allowed: true });
        expect(checkRateLimit).toHaveBeenCalledWith(mockConfig, identifier);
      }

      expect(checkRateLimit).toHaveBeenCalledTimes(identifiers.length);
    });

    test("should pass weighted usage to the rate limiter", async () => {
      vi.mocked(checkRateLimit).mockResolvedValue(ok({ allowed: true }));

      await expect(applyRateLimit(mockConfig, mockIdentifier, 25)).resolves.toEqual({ allowed: true });

      expect(checkRateLimit).toHaveBeenCalledWith(mockConfig, mockIdentifier, 25);
    });
  });

  describe("assertRateLimitAvailable", () => {
    const mockConfig = {
      interval: 300,
      allowedPerInterval: 5,
      namespace: "test",
    };

    test("should allow request when peek says capacity remains", async () => {
      vi.mocked(peekRateLimit).mockResolvedValue(ok({ allowed: true }));

      await expect(assertRateLimitAvailable(mockConfig, "test-identifier")).resolves.toEqual({
        allowed: true,
      });

      expect(peekRateLimit).toHaveBeenCalledWith(mockConfig, "test-identifier");
      expect(checkRateLimit).not.toHaveBeenCalled();
    });

    test("should reject request when peek says limit is exhausted", async () => {
      vi.mocked(peekRateLimit).mockResolvedValue(ok({ allowed: false, retryAfter: 60 }));

      await expect(assertRateLimitAvailable(mockConfig, "test-identifier")).rejects.toThrow(
        "Maximum number of requests reached. Please try again later."
      );
    });
  });

  describe("rate limit reservations", () => {
    const mockConfig = {
      interval: 300,
      allowedPerInterval: 5,
      namespace: "test",
    };
    const reservation = {
      identifier: "test-identifier",
      key: "rate-limit-key",
      namespace: "test",
      requested: 5,
      settled: false,
    };

    test("returns a receipt for an allowed reservation", async () => {
      vi.mocked(reserveRateLimit).mockResolvedValue(
        ok({ allowed: true, retryAfter: undefined, reservation })
      );

      await expect(reserveRateLimitUsage(mockConfig, "test-identifier", 5)).resolves.toBe(reservation);
      expect(reserveRateLimit).toHaveBeenCalledWith(mockConfig, "test-identifier", 5);
    });

    test("rejects a reservation when capacity is exhausted", async () => {
      vi.mocked(reserveRateLimit).mockResolvedValue(ok({ allowed: false, retryAfter: 60 }));

      await expect(reserveRateLimitUsage(mockConfig, "test-identifier", 5)).rejects.toThrow(
        "Maximum number of requests reached. Please try again later."
      );
    });

    test("settles an existing receipt and ignores a fail-open reservation", async () => {
      await settleRateLimitUsage(reservation, 2);
      await settleRateLimitUsage(undefined, 0);

      expect(settleRateLimit).toHaveBeenCalledOnce();
      expect(settleRateLimit).toHaveBeenCalledWith(reservation, 2);
    });
  });

  describe("applyIPRateLimit", () => {
    test("should be a convenience function that gets IP and applies rate limit", async () => {
      // This is an integration test - the function calls getClientIdentifier internally
      // and then calls applyRateLimit, which we've already tested extensively
      const mockConfig = {
        interval: 3600,
        allowedPerInterval: 100,
        namespace: "test:page",
      };

      // Mock the IP getting functions
      vi.mocked(getClientIpFromHeaders).mockResolvedValue("192.168.1.1");
      vi.mocked(hashString).mockReturnValue("hashed-ip-123");
      vi.mocked(checkRateLimit).mockResolvedValue(ok({ allowed: true }));

      await expect(applyIPRateLimit(mockConfig)).resolves.toEqual({ allowed: true });

      expect(getClientIpFromHeaders).toHaveBeenCalledTimes(1);
      expect(hashString).toHaveBeenCalledWith("192.168.1.1");
      expect(checkRateLimit).toHaveBeenCalledWith(mockConfig, "hashed-ip-123");
    });

    test("should propagate errors from getClientIdentifier", async () => {
      const mockConfig = {
        interval: 3600,
        allowedPerInterval: 100,
        namespace: "test:page",
      };

      vi.mocked(getClientIpFromHeaders).mockRejectedValue(new Error("IP fetch failed"));

      await expect(applyIPRateLimit(mockConfig)).rejects.toThrow("IP fetch failed");
    });

    test("should propagate rate limit exceeded errors", async () => {
      const mockConfig = {
        interval: 3600,
        allowedPerInterval: 100,
        namespace: "test:page",
      };

      vi.mocked(getClientIpFromHeaders).mockResolvedValue("192.168.1.1");
      vi.mocked(hashString).mockReturnValue("hashed-ip-123");
      vi.mocked(checkRateLimit).mockResolvedValue(ok({ allowed: false }));

      await expect(applyIPRateLimit(mockConfig)).rejects.toThrow(
        "Maximum number of requests reached. Please try again later."
      );
    });

    test("skips the shared untrusted identity only when asked, without counting it", async () => {
      const mockConfig = { interval: 60, allowedPerInterval: 120, namespace: "auth:saml-callback" };
      vi.mocked(getClientIpFromHeaders).mockResolvedValue("untrusted-client-ip");
      vi.mocked(hashString).mockReturnValue("hashed-untrusted");
      vi.mocked(checkRateLimit).mockResolvedValue(ok({ allowed: true }));

      await expect(applyIPRateLimit(mockConfig, { skipUntrustedClient: true })).resolves.toEqual({
        allowed: true,
      });
      expect(checkRateLimit).not.toHaveBeenCalled();
      expect(getClientIpFromHeaders).toHaveBeenCalledTimes(1);

      // Without the option the shared identity is counted like any other.
      await applyIPRateLimit(mockConfig);
      expect(checkRateLimit).toHaveBeenCalledWith(mockConfig, "hashed-untrusted");
    });

    test("still counts a trusted client when asked to skip untrusted ones", async () => {
      const mockConfig = { interval: 60, allowedPerInterval: 120, namespace: "auth:saml-callback" };
      vi.mocked(getClientIpFromHeaders).mockResolvedValue("203.0.113.7");
      vi.mocked(hashString).mockReturnValue("hashed-trusted");
      vi.mocked(checkRateLimit).mockResolvedValue(ok({ allowed: true }));

      await applyIPRateLimit(mockConfig, { skipUntrustedClient: true });

      expect(checkRateLimit).toHaveBeenCalledWith(mockConfig, "hashed-trusted");
    });
  });

  describe("applyClientRateLimit", () => {
    test("should apply compound environment/IP and environment aggregate rate limits", async () => {
      vi.mocked(getClientIpFromHeaders).mockResolvedValue("192.168.1.1");
      vi.mocked(hashString).mockReturnValue("hashed-ip-123");
      vi.mocked(checkRateLimit).mockResolvedValue(ok({ allowed: true }));

      await expect(applyClientRateLimit("env_1")).resolves.toEqual({ allowed: true });

      expect(checkRateLimit).toHaveBeenNthCalledWith(1, rateLimitConfigs.api.client, "env_1:hashed-ip-123");
      expect(checkRateLimit).toHaveBeenNthCalledWith(2, rateLimitConfigs.api.clientEnvironment, "env_1");
    });

    test("should apply custom config only to the compound environment/IP check", async () => {
      const customConfig = {
        interval: 60,
        allowedPerInterval: 5,
        namespace: "storage:upload",
      };

      vi.mocked(getClientIpFromHeaders).mockResolvedValue("192.168.1.1");
      vi.mocked(hashString).mockReturnValue("hashed-ip-123");
      vi.mocked(checkRateLimit).mockResolvedValue(ok({ allowed: true }));

      await expect(applyClientRateLimit("env_1", customConfig)).resolves.toEqual({ allowed: true });

      expect(checkRateLimit).toHaveBeenNthCalledWith(1, customConfig, "env_1:hashed-ip-123");
      expect(checkRateLimit).toHaveBeenNthCalledWith(2, rateLimitConfigs.api.clientEnvironment, "env_1");
    });

    test("should throw when the compound environment/IP rate limit is exceeded", async () => {
      vi.mocked(getClientIpFromHeaders).mockResolvedValue("192.168.1.1");
      vi.mocked(hashString).mockReturnValue("hashed-ip-123");
      vi.mocked(checkRateLimit).mockResolvedValue(ok({ allowed: false }));

      await expect(applyClientRateLimit("env_1")).rejects.toThrow(
        "Maximum number of requests reached. Please try again later."
      );

      expect(checkRateLimit).toHaveBeenCalledTimes(1);
      expect(checkRateLimit).toHaveBeenCalledWith(rateLimitConfigs.api.client, "env_1:hashed-ip-123");
    });

    test("should throw when the environment aggregate rate limit is exceeded", async () => {
      vi.mocked(getClientIpFromHeaders).mockResolvedValue("192.168.1.1");
      vi.mocked(hashString).mockReturnValue("hashed-ip-123");
      vi.mocked(checkRateLimit)
        .mockResolvedValueOnce(ok({ allowed: true }))
        .mockResolvedValueOnce(ok({ allowed: false }));

      await expect(applyClientRateLimit("env_1")).rejects.toThrow(
        "Maximum number of requests reached. Please try again later."
      );

      expect(checkRateLimit).toHaveBeenNthCalledWith(1, rateLimitConfigs.api.client, "env_1:hashed-ip-123");
      expect(checkRateLimit).toHaveBeenNthCalledWith(2, rateLimitConfigs.api.clientEnvironment, "env_1");
    });
  });
});
