/**
 * @jest-environment node
 */

import { POST } from "../route";

jest.mock("@clerk/nextjs/server", () => ({
  auth: jest.fn(),
}));

jest.mock("@/lib/database", () => ({
  getDatabase: jest.fn(),
}));

jest.mock("@/lib/sync-user", () => ({
  ensureUserSynced: jest.fn(),
}));

jest.mock("@/lib/ai/ai-context", () => ({
  buildAIContext: jest.fn(),
}));

jest.mock("@/lib/ai/prompt-builder", () => ({
  buildEnhancedPrompt: jest.fn(),
  buildBasicPrompt: jest.fn(),
}));

jest.mock("@/lib/logger", () => ({
  info: jest.fn(),
  warn: jest.fn(),
  error: jest.fn(),
  debug: jest.fn(),
}));

describe("POST /api/recommendations/generate authz", () => {
  const mockAuth = require("@clerk/nextjs/server").auth as jest.Mock;
  const mockGetDatabase = require("@/lib/database").getDatabase as jest.Mock;
  const mockEnsureUserSynced = require("@/lib/sync-user")
    .ensureUserSynced as jest.Mock;

  const mockDb = {
    getUserById: jest.fn(),
    getFitnessProfileByUserId: jest.fn(),
  };

  beforeEach(() => {
    jest.clearAllMocks();
    mockGetDatabase.mockResolvedValue(mockDb);
  });

  it("returns 401 when unauthenticated", async () => {
    mockAuth.mockResolvedValue({ userId: null });

    const req = new Request("http://localhost/api/recommendations/generate", {
      method: "POST",
      body: JSON.stringify({ userId: "client_1" }),
      headers: { "Content-Type": "application/json" },
    });

    const res = await POST(req);
    expect(res.status).toBe(401);
  });

  it("returns 403 when staff accesses user from another gym", async () => {
    mockAuth.mockResolvedValue({ userId: "admin_1" });
    mockEnsureUserSynced.mockResolvedValue({
      id: "admin_1",
      role: "admin",
      gymId: "gym_a",
    });
    mockDb.getUserById.mockResolvedValue({
      id: "client_1",
      gymId: "gym_b",
    });

    const req = new Request("http://localhost/api/recommendations/generate", {
      method: "POST",
      body: JSON.stringify({ userId: "client_1" }),
      headers: { "Content-Type": "application/json" },
    });

    const res = await POST(req);
    expect(res.status).toBe(403);
  });
});
