// @ts-nocheck

import { createClient } from "@supabase/supabase-js";
import { describe, expect, it } from "vitest";
import {
  authenticateFromHeader,
  authenticateUser,
  validateAuthHeader,
} from "../../helpers/auth.js";

describe("Auth Helper Tests", () => {
  describe("validateAuthHeader", () => {
    it("should reject undefined header", () => {
      const result = validateAuthHeader(undefined);

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Missing or invalid authorization header");
        expect(result.statusCode).toBe(401);
      }
    });

    it("should reject empty string header", () => {
      const result = validateAuthHeader("");

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Missing or invalid authorization header");
        expect(result.statusCode).toBe(401);
      }
    });

    it("should reject header without Bearer prefix", () => {
      const result = validateAuthHeader("Token abc123");

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Missing or invalid authorization header");
        expect(result.statusCode).toBe(401);
      }
    });

    it("should reject header with only Bearer prefix", () => {
      const result = validateAuthHeader("Bearer ");

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Missing or invalid authorization header");
        expect(result.statusCode).toBe(401);
      }
    });

    it("should reject header with Bearer but only whitespace", () => {
      const result = validateAuthHeader("Bearer   ");

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Missing or invalid authorization header");
        expect(result.statusCode).toBe(401);
      }
    });

    it("should accept valid Bearer token", () => {
      const token = "valid-token-abc-123";
      const result = validateAuthHeader(`Bearer ${token}`);

      expect(result.success).toBe(true);
      if (result.success) {
        expect(result.token).toBe(token);
      }
    });

    it("should extract token correctly with extra spaces", () => {
      const token = "valid-token-with-spaces";
      const result = validateAuthHeader(`Bearer ${token}`);

      expect(result.success).toBe(true);
      if (result.success) {
        expect(result.token).toBe(token);
      }
    });

    it("should handle long tokens", () => {
      const token = "a".repeat(500);
      const result = validateAuthHeader(`Bearer ${token}`);

      expect(result.success).toBe(true);
      if (result.success) {
        expect(result.token).toBe(token);
        expect(result.token.length).toBe(500);
      }
    });

    it("should handle tokens with special characters", () => {
      const token =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
      const result = validateAuthHeader(`Bearer ${token}`);

      expect(result.success).toBe(true);
      if (result.success) {
        expect(result.token).toBe(token);
      }
    });

    it("should be case sensitive for Bearer prefix", () => {
      const result = validateAuthHeader("bearer token123");

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Missing or invalid authorization header");
      }
    });

    it("should reject BEARER in uppercase", () => {
      const result = validateAuthHeader("BEARER token123");

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Missing or invalid authorization header");
      }
    });
  });

  describe("authenticateUser", () => {
    // Create a test Supabase client (will fail auth in test environment)
    const supabase = createClient(
      process.env.SUPABASE_URL || "https://test.supabase.co",
      process.env.SUPABASE_SERVICE_ROLE_KEY || "test-key"
    );

    it("should reject invalid token", async () => {
      const result = await authenticateUser(supabase, "invalid-token-xyz");

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Invalid or expired token");
        expect(result.statusCode).toBe(401);
      }
    });

    it("should reject empty token", async () => {
      const result = await authenticateUser(supabase, "");

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Invalid or expired token");
        expect(result.statusCode).toBe(401);
      }
    });

    it("should reject malformed token", async () => {
      const result = await authenticateUser(supabase, "not-a-valid-jwt");

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Invalid or expired token");
        expect(result.statusCode).toBe(401);
      }
    });

    it("should handle very long invalid tokens", async () => {
      const longToken = "x".repeat(10000);
      const result = await authenticateUser(supabase, longToken);

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Invalid or expired token");
        expect(result.statusCode).toBe(401);
      }
    });
  });

  describe("authenticateFromHeader", () => {
    const supabase = createClient(
      process.env.SUPABASE_URL || "https://test.supabase.co",
      process.env.SUPABASE_SERVICE_ROLE_KEY || "test-key"
    );

    it("should fail on missing header", async () => {
      const result = await authenticateFromHeader(undefined, supabase);

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Missing or invalid authorization header");
        expect(result.statusCode).toBe(401);
      }
    });

    it("should fail on invalid header format", async () => {
      const result = await authenticateFromHeader("Token abc123", supabase);

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Missing or invalid authorization header");
        expect(result.statusCode).toBe(401);
      }
    });

    it("should fail on invalid token with valid header format", async () => {
      const result = await authenticateFromHeader("Bearer invalid-token", supabase);

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error).toBe("Invalid or expired token");
        expect(result.statusCode).toBe(401);
      }
    });

    it("should handle header with empty Bearer token", async () => {
      const result = await authenticateFromHeader("Bearer ", supabase);

      expect(result.success).toBe(false);
      if (!result.success) {
        // Should fail at header validation stage
        expect(result.error).toBe("Missing or invalid authorization header");
        expect(result.statusCode).toBe(401);
      }
    });

    it("should return 401 for all auth failures", async () => {
      const testCases = [undefined, "", "Token abc", "bearer token", "Bearer ", "Bearer invalid"];

      for (const testCase of testCases) {
        const result = await authenticateFromHeader(testCase, supabase);
        expect(result.success).toBe(false);
        if (!result.success) {
          expect(result.statusCode).toBe(401);
        }
      }
    });
  });

  describe("Edge Cases", () => {
    it("validateAuthHeader should handle null coerced to string", () => {
      // biome-ignore lint/suspicious/noExplicitAny: Testing runtime type coercion
      const result = validateAuthHeader(null as any);

      expect(result.success).toBe(false);
    });

    it("validateAuthHeader should handle number coerced to string", () => {
      // biome-ignore lint/suspicious/noExplicitAny: Testing runtime type coercion
      const result = validateAuthHeader(123 as any);

      expect(result.success).toBe(false);
    });

    it("validateAuthHeader should handle object coerced to string", () => {
      // biome-ignore lint/suspicious/noExplicitAny: Testing runtime type coercion
      const result = validateAuthHeader({ token: "abc" } as any);

      expect(result.success).toBe(false);
    });
  });

  describe("Security", () => {
    it("should not leak token information in errors", () => {
      const sensitiveToken = "super-secret-token-12345";
      const result = validateAuthHeader(`Invalid ${sensitiveToken}`);

      expect(result.success).toBe(false);
      if (!result.success) {
        // Error message should not contain the token
        assert.ok(!result.error.includes(sensitiveToken));
        assert.ok(!result.error.includes("super-secret"));
      }
    });

    it("should handle SQL injection attempts gracefully", () => {
      const maliciousToken = "'; DROP TABLE users; --";
      const result = validateAuthHeader(`Bearer ${maliciousToken}`);

      // Should extract token but not execute anything
      expect(result.success).toBe(true);
      if (result.success) {
        expect(result.token).toBe(maliciousToken);
      }
    });

    it("should handle XSS attempts in token", () => {
      const xssToken = "<script>alert('xss')</script>";
      const result = validateAuthHeader(`Bearer ${xssToken}`);

      expect(result.success).toBe(true);
      if (result.success) {
        // Token is extracted as-is, validation happens at auth layer
        expect(result.token).toBe(xssToken);
      }
    });
  });
});
