/**
 * @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/logger", () => ({
  info: jest.fn(),
  warn: jest.fn(),
  error: jest.fn(),
  debug: jest.fn(),
}));

describe("POST /api/recommendations/approve 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 = {
    getAllRecommendations: jest.fn(),
    getUserById: jest.fn(),
    updateRecommendation: jest.fn(),
    createNotification: jest.fn(),
  };

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

  it("returns 403 for non-staff role", async () => {
    mockAuth.mockResolvedValue({ userId: "client_1" });
    mockEnsureUserSynced.mockResolvedValue({
      id: "client_1",
      role: "client",
      gymId: "gym_a",
    });

    const req = new Request("http://localhost/api/recommendations/approve", {
      method: "POST",
      body: JSON.stringify({ recommendationId: "rec_1", status: "approved" }),
      headers: { "Content-Type": "application/json" },
    });

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

  it("returns 403 for cross-gym approval by admin", async () => {
    mockAuth.mockResolvedValue({ userId: "admin_1" });
    mockEnsureUserSynced.mockResolvedValue({
      id: "admin_1",
      role: "admin",
      gymId: "gym_a",
    });
    mockDb.getAllRecommendations.mockResolvedValue([
      { id: "rec_1", userId: "client_1" },
    ]);
    mockDb.getUserById.mockResolvedValue({ id: "client_1", gymId: "gym_b" });

    const req = new Request("http://localhost/api/recommendations/approve", {
      method: "POST",
      body: JSON.stringify({ recommendationId: "rec_1", status: "approved" }),
      headers: { "Content-Type": "application/json" },
    });

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