/**
 * @jest-environment node
 */

import { NextRequest } from "next/server";
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/notifications 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(),
    createNotification: jest.fn(),
  };

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

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

    const request = new NextRequest("http://localhost/api/notifications", {
      method: "POST",
      body: JSON.stringify({
        targetUserId: "client_2",
        title: "Hello",
        message: "Test",
        type: "system",
      }),
    });

    const response = await POST(request);
    expect(response.status).toBe(403);
  });

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

    const request = new NextRequest("http://localhost/api/notifications", {
      method: "POST",
      body: JSON.stringify({
        targetUserId: "client_2",
        title: "Hello",
        message: "Test",
        type: "system",
      }),
    });

    const response = await POST(request);
    expect(response.status).toBe(403);
  });
});
