/**
 * Appointment Type Categories API
 *
 * GET /api/dashboard/appointment-types/categories
 *   Returns the unique service categories for the authenticated user's organisation.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveDataOwnerId } from "@/lib/utils/organization-data";
import { AppointmentTypeService } from "@/lib/services/appointment-type.service";
import { logger } from "@/lib/logger";

const scopedLogger = logger.scope("AppointmentTypeCategoriesAPI");

export const dynamic = "force-dynamic";

export async function GET(request: NextRequest) {
  try {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const user = await getAuthenticatedUser(request, auth as any);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const result = await getEffectiveDataOwnerId(user.userId);
    const organizationId = result.organizationId ?? null;

    if (!organizationId) {
      return NextResponse.json(
        { success: false, error: "Organization not found" },
        { status: 404 },
      );
    }

    const categories =
      await AppointmentTypeService.getCategoriesForOrg(organizationId);

    scopedLogger.info("Categories retrieved", {
      userId: user.userId,
      organizationId,
      count: categories.length,
    });

    return NextResponse.json({ success: true, categories });
  } catch (error) {
    scopedLogger.error("Failed to retrieve categories", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
