import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getSuggestedTypes } from "@/lib/services/appointment-type-seeder";

export const dynamic = "force-dynamic";

export async function GET(request: NextRequest) {
  const user = await getAuthenticatedUser(request, auth);
  if (!user) {
    return NextResponse.json(
      { success: false, error: "Unauthorized" },
      { status: 401 },
    );
  }

  const org = await prisma.organizations.findFirst({
    where: { ownerId: user.userId },
    select: { id: true },
  });
  if (!org) {
    return NextResponse.json(
      { success: false, error: "Organization not found" },
      { status: 404 },
    );
  }

  const [dbUser, existingTypes] = await Promise.all([
    prisma.users.findUnique({
      where: { id: user.userId },
      select: { industry: true },
    }),
    prisma.appointment_types.findMany({
      where: { organizationId: org.id },
      select: { nameEn: true },
    }),
  ]);

  const existingNames = existingTypes.map((t: { nameEn: string }) => t.nameEn);
  const suggestions = getSuggestedTypes(dbUser?.industry, existingNames);

  return NextResponse.json({
    success: true,
    suggestions,
    industry: dbUser?.industry ?? null,
  });
}
