/**
 * Support Tickets API Authentication Tests
 *
 * These tests ensure the support ticket API routes use the unified
 * authentication helper that supports both NextAuth and custom JWT tokens.
 *
 * CRITICAL: These tests prevent regression of the authentication bug where
 * users logged in via OTP (auth_token cookie) couldn't access support tickets.
 *
 * Bug History:
 * - APIs were using only NextAuth `auth()` function
 * - Users logged in via OTP have `auth_token` cookie, not NextAuth session
 * - Fix: Use `getAuthenticatedUser(request, auth)` from auth-helpers.util.ts
 */

import * as fs from "fs";
import * as path from "path";

// Auth patterns changed with Convex migration - code analysis tests outdated
describe.skip("Support Tickets API - Authentication Pattern", () => {
  const apiBasePath = path.resolve(process.cwd(), "app/api/support/tickets");

  describe("Main tickets route (GET/POST)", () => {
    const routePath = path.join(apiBasePath, "route.ts");

    it("should import getAuthenticatedUser from auth-helpers.util", () => {
      const content = fs.readFileSync(routePath, "utf-8");

      // Must import from the correct utility
      expect(content).toContain("from '@/lib/utils/auth-helpers.util'");
      expect(content).toContain("getAuthenticatedUser");
    });

    it("should import auth from @/lib/auth", () => {
      const content = fs.readFileSync(routePath, "utf-8");

      // Must import auth to pass to getAuthenticatedUser
      expect(content).toContain("from '@/lib/auth'");
    });

    it("should use getAuthenticatedUser(request, auth) pattern", () => {
      const content = fs.readFileSync(routePath, "utf-8");

      // The correct pattern: getAuthenticatedUser(request, auth)
      expect(content).toMatch(
        /getAuthenticatedUser\s*\(\s*request\s*,\s*auth\s*\)/,
      );
    });

    it("should check authResult.userId (not authResult.user.id)", () => {
      const content = fs.readFileSync(routePath, "utf-8");

      // The utility returns { userId, email, ... } not { user: { id } }
      expect(content).toContain("authResult?.userId");
      // Should NOT use the old pattern
      expect(content).not.toContain("authResult?.user?.id");
    });

    it("should NOT use only auth() without getAuthenticatedUser", () => {
      const content = fs.readFileSync(routePath, "utf-8");

      // Should not have standalone `await auth()` calls for route authentication
      // (it's ok to import auth and pass to getAuthenticatedUser)
      const lines = content.split("\n");
      const authOnlyPattern = /const\s+session\s*=\s*await\s+auth\(\)/;

      for (const line of lines) {
        expect(line).not.toMatch(authOnlyPattern);
      }
    });
  });

  describe("Ticket detail route (GET /[id])", () => {
    const routePath = path.join(apiBasePath, "[id]", "route.ts");

    it("should import getAuthenticatedUser from auth-helpers.util", () => {
      const content = fs.readFileSync(routePath, "utf-8");
      expect(content).toContain("from '@/lib/utils/auth-helpers.util'");
      expect(content).toContain("getAuthenticatedUser");
    });

    it("should use getAuthenticatedUser(request, auth) pattern", () => {
      const content = fs.readFileSync(routePath, "utf-8");
      expect(content).toMatch(
        /getAuthenticatedUser\s*\(\s*request\s*,\s*auth\s*\)/,
      );
    });

    it("should check authResult.userId", () => {
      const content = fs.readFileSync(routePath, "utf-8");
      expect(content).toContain("authResult?.userId");
    });
  });

  describe("Ticket messages route (POST /[id]/messages)", () => {
    const routePath = path.join(apiBasePath, "[id]", "messages", "route.ts");

    it("should import getAuthenticatedUser from auth-helpers.util", () => {
      const content = fs.readFileSync(routePath, "utf-8");
      expect(content).toContain("from '@/lib/utils/auth-helpers.util'");
      expect(content).toContain("getAuthenticatedUser");
    });

    it("should use getAuthenticatedUser(request, auth) pattern", () => {
      const content = fs.readFileSync(routePath, "utf-8");
      expect(content).toMatch(
        /getAuthenticatedUser\s*\(\s*request\s*,\s*auth\s*\)/,
      );
    });

    it("should check authResult.userId", () => {
      const content = fs.readFileSync(routePath, "utf-8");
      expect(content).toContain("authResult?.userId");
    });
  });
});

describe("Support Tickets API - Required Exports", () => {
  const apiBasePath = path.resolve(process.cwd(), "app/api/support/tickets");

  describe("Main route exports", () => {
    it("should export GET function", () => {
      const routePath = path.join(apiBasePath, "route.ts");
      const content = fs.readFileSync(routePath, "utf-8");
      expect(content).toMatch(/export\s+(async\s+)?function\s+GET/);
    });

    it("should export POST function", () => {
      const routePath = path.join(apiBasePath, "route.ts");
      const content = fs.readFileSync(routePath, "utf-8");
      expect(content).toMatch(/export\s+(async\s+)?function\s+POST/);
    });
  });

  describe("Ticket detail route exports", () => {
    it("should export GET function", () => {
      const routePath = path.join(apiBasePath, "[id]", "route.ts");
      const content = fs.readFileSync(routePath, "utf-8");
      expect(content).toMatch(/export\s+(async\s+)?function\s+GET/);
    });
  });

  describe("Messages route exports", () => {
    it("should export POST function", () => {
      const routePath = path.join(apiBasePath, "[id]", "messages", "route.ts");
      const content = fs.readFileSync(routePath, "utf-8");
      expect(content).toMatch(/export\s+(async\s+)?function\s+POST/);
    });
  });
});

// Auth helpers API changed with Convex migration
describe.skip("Auth Helpers Utility - Dual Auth Support", () => {
  const helperPath = path.resolve(
    process.cwd(),
    "lib/utils/auth-helpers.util.ts",
  );

  it("should export getAuthenticatedUser function", () => {
    const content = fs.readFileSync(helperPath, "utf-8");
    expect(content).toMatch(
      /export\s+(async\s+)?function\s+getAuthenticatedUser/,
    );
  });

  it("should check for NextAuth session first", () => {
    const content = fs.readFileSync(helperPath, "utf-8");
    // Should call the auth function
    expect(content).toContain("await authFunction()");
    expect(content).toContain("session?.user");
  });

  it("should fallback to auth_token cookie", () => {
    const content = fs.readFileSync(helperPath, "utf-8");
    // Should check for auth_token cookie
    expect(content).toContain("'auth_token'");
    expect(content).toContain("request.cookies.get");
  });

  it("should return AuthenticatedUser interface with userId", () => {
    const content = fs.readFileSync(helperPath, "utf-8");
    // Interface should have userId
    expect(content).toContain("interface AuthenticatedUser");
    expect(content).toContain("userId: string");
    expect(content).toContain("email: string");
    expect(content).toContain("source: 'nextauth' | 'auth_token'");
  });

  it("should decode base64 auth_token", () => {
    const content = fs.readFileSync(helperPath, "utf-8");
    // Should decode base64 token
    expect(content).toContain("Buffer.from");
    expect(content).toContain("'base64'");
  });
});
