import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";

// Mock auth dependencies
jest.mock("@/lib/auth", () => ({
  auth: jest.fn(),
}));

jest.mock("@/lib/utils/auth-helpers.util", () => ({
  getAuthenticatedUser: jest.fn(),
}));

// Set up prisma mock tables on the shared reference
// (same pattern used by appointment-type-seeder.test.ts)
const mockOrgFindFirst = jest.fn();
const mockUserFindUnique = jest.fn();
const mockTypeFindMany = jest.fn();

(prisma as Record<string, unknown>).organizations = {
  findFirst: mockOrgFindFirst,
};
(prisma as Record<string, unknown>).users = { findUnique: mockUserFindUnique };
(prisma as Record<string, unknown>).appointment_types = {
  findMany: mockTypeFindMany,
};

import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { GET } from "@/app/api/dashboard/appointment-types/suggested/route";

describe("GET /api/dashboard/appointment-types/suggested", () => {
  beforeEach(() => jest.clearAllMocks());

  it("returns 401 when not authenticated", async () => {
    (getAuthenticatedUser as jest.Mock).mockResolvedValue(null);
    const req = new NextRequest(
      "http://localhost/api/dashboard/appointment-types/suggested",
    );
    const res = await GET(req);
    expect(res.status).toBe(401);
  });

  it("returns filtered suggestions for dental industry", async () => {
    (getAuthenticatedUser as jest.Mock).mockResolvedValue({ userId: "user-1" });
    mockOrgFindFirst.mockResolvedValue({ id: "org-1" });
    mockUserFindUnique.mockResolvedValue({ industry: "dental" });
    mockTypeFindMany.mockResolvedValue([{ nameEn: "Root Canal" }]);

    const req = new NextRequest(
      "http://localhost/api/dashboard/appointment-types/suggested",
    );
    const res = await GET(req);
    const body = await res.json();

    expect(res.status).toBe(200);
    expect(body.suggestions).toBeDefined();
    expect(
      body.suggestions.every(
        (s: { nameEn: string }) => s.nameEn !== "Root Canal",
      ),
    ).toBe(true);
  });

  it("returns 404 when org not found", async () => {
    (getAuthenticatedUser as jest.Mock).mockResolvedValue({ userId: "user-1" });
    mockOrgFindFirst.mockResolvedValue(null);

    const req = new NextRequest(
      "http://localhost/api/dashboard/appointment-types/suggested",
    );
    const res = await GET(req);
    expect(res.status).toBe(404);
  });
});
