/**
 * Regression Test Suite: Dashboard API Dual Authentication Coverage
 *
 * CRITICAL: Ensures ALL dashboard APIs support BOTH authentication methods
 *
 * This test prevents the regression where APIs only accepted NextAuth sessions,
 * causing OTP users to see errors or missing data.
 *
 * Test Strategy:
 * 1. List all dashboard-related API endpoints
 * 2. For each endpoint, verify it accepts both NextAuth AND auth_token
 * 3. Verify it properly rejects unauthenticated requests
 *
 * @see BILLING_AUTH_FIX.md
 */

import { createAuthTokenCookie } from "../helpers/auth-test-helpers";

// Makes HTTP requests to localhost:9000 - requires running server
describe.skip("Dashboard API Dual Authentication Coverage", () => {
  const TEST_USER_ID = "test-user-123";
  const TEST_EMAIL = "test@example.com";

  /**
   * All dashboard APIs that require authentication
   * Format: [endpoint, method, description]
   */
  const DASHBOARD_APIS = [
    // Billing APIs
    ["/api/subscription/details", "GET", "Subscription details"],
    ["/api/user/package-status", "GET", "Package status"],
    ["/api/billing/current", "GET", "Current billing"],
    ["/api/billing/plans", "GET", "Available plans"],
    ["/api/billing/invoices", "GET", "Invoice list"],

    // Dashboard Data APIs
    ["/api/analytics/metrics", "GET", "Analytics metrics"],
    ["/api/conversations", "GET", "WhatsApp conversations"],
    ["/api/bookings", "GET", "Appointment bookings"],
    ["/api/notifications", "GET", "User notifications"],
    ["/api/integrations", "GET", "Integration status"],

    // User Profile APIs
    ["/api/user/profile", "GET", "User profile"],
    ["/api/user/preferences", "GET", "User preferences"],
    ["/api/user/sessions", "GET", "Active sessions"],
    ["/api/user/audit-log", "GET", "Audit log"],
  ] as const;

  describe("Authentication Method Support Matrix", () => {
    test.each(DASHBOARD_APIS)(
      "%s (%s) - %s: should support auth_token cookie",
      async (endpoint, method) => {
        const authToken = createAuthTokenCookie(TEST_USER_ID, TEST_EMAIL);

        const response = await fetch(`http://localhost:9000${endpoint}`, {
          method,
          headers: {
            Cookie: `auth_token=${authToken}`,
          },
        });

        // Should NOT return 401 Unauthorized
        // May return 404 (no data), 200 (success), or other valid status
        // But 401 means auth failed, which is what we're testing against
        if (response.status === 401) {
          const data = await response.json().catch(() => ({}));
          console.error(`❌ ${endpoint} returned 401 with auth_token:`, data);
        }

        expect(response.status).not.toBe(401);
      },
    );

    it("should list all tested endpoints", () => {
      console.log("\n📋 Tested Dashboard APIs:");
      DASHBOARD_APIS.forEach(([endpoint, method, desc]) => {
        console.log(`  ✓ ${method} ${endpoint} - ${desc}`);
      });
      console.log(`\n✅ Total: ${DASHBOARD_APIS.length} endpoints tested\n`);

      expect(DASHBOARD_APIS.length).toBeGreaterThanOrEqual(14);
    });
  });

  describe("Critical Billing Endpoints - Detailed Tests", () => {
    describe("/api/subscription/details", () => {
      it("should return subscription data with auth_token", async () => {
        const authToken = createAuthTokenCookie(TEST_USER_ID, TEST_EMAIL);

        const response = await fetch(
          "http://localhost:9000/api/subscription/details",
          {
            headers: {
              Cookie: `auth_token=${authToken}`,
            },
          },
        );

        // Either 200 (has subscription) or 404 (no subscription) is acceptable
        // 401 means auth failed - NOT acceptable
        expect([200, 404]).toContain(response.status);

        if (response.status === 401) {
          const data = await response.json();
          throw new Error(`API returned 401: ${data.error}`);
        }
      });
    });

    describe("/api/user/package-status", () => {
      it("should return package status with auth_token", async () => {
        const authToken = createAuthTokenCookie(TEST_USER_ID, TEST_EMAIL);

        const response = await fetch(
          "http://localhost:9000/api/user/package-status",
          {
            headers: {
              Cookie: `auth_token=${authToken}`,
            },
          },
        );

        expect([200, 404]).toContain(response.status);

        if (response.status === 401) {
          const data = await response.json();
          throw new Error(`API returned 401: ${data.error}`);
        }
      });
    });
  });

  describe("Error Case: Missing Authentication", () => {
    it("should return 401 for all endpoints without any auth", async () => {
      const criticalEndpoints = [
        "/api/subscription/details",
        "/api/user/package-status",
        "/api/billing/current",
      ];

      for (const endpoint of criticalEndpoints) {
        const response = await fetch(`http://localhost:9000${endpoint}`, {
          // No auth headers or cookies
        });

        expect(response.status).toBe(401);
      }
    });
  });
});

/**
 * Smoke Test: Quick validation that auth helpers are available
 */
describe("Dual Auth Helper Availability", () => {
  it("should have getAuthenticatedEmail helper", async () => {
    const { getAuthenticatedEmail } =
      await import("@/lib/utils/auth-helpers.util");
    expect(typeof getAuthenticatedEmail).toBe("function");
  });

  it("should have getAuthenticatedUser helper", async () => {
    const { getAuthenticatedUser } =
      await import("@/lib/utils/auth-helpers.util");
    expect(typeof getAuthenticatedUser).toBe("function");
  });

  it("should export AuthenticatedUser interface", async () => {
    const module = await import("@/lib/utils/auth-helpers.util");
    expect(module).toHaveProperty("getAuthenticatedUser");
  });
});

/**
 * Documentation Test: Ensure fix is documented
 */
// BILLING_AUTH_FIX.md no longer exists
describe.skip("Regression Prevention Documentation", () => {
  it("should have BILLING_AUTH_FIX.md documentation", async () => {
    const fs = require("fs");
    const path = require("path");

    const docPath = path.join(process.cwd(), "BILLING_AUTH_FIX.md");
    const exists = fs.existsSync(docPath);

    expect(exists).toBe(true);

    if (exists) {
      const content = fs.readFileSync(docPath, "utf-8");
      expect(content).toContain("getAuthenticatedEmail");
      expect(content).toContain("auth_token");
      expect(content).toContain("NextAuth");
    }
  });
});
