import { NextResponse } from "next/server";

import { requireApiAccess } from "@/lib/authorization";
import { prisma } from "@/lib/prisma";

export async function GET(request: Request) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;

  const [washingPlaces, grades, warehouses] = await Promise.all([
    prisma.washingPlace.findMany({
      where: { status: "ACTIVE" },
      orderBy: [{ name: "asc" }],
      select: {
        id: true,
        code: true,
        name: true
      }
    }),
    prisma.grade.findMany({
      where: { status: "ACTIVE" },
      orderBy: [{ name: "asc" }],
      select: {
        id: true,
        code: true,
        name: true
      }
    }),
    prisma.warehouse.findMany({
      where: { status: "ACTIVE" },
      include: {
        locations: {
          where: { status: "ACTIVE" },
          orderBy: [{ name: "asc" }],
          select: {
            id: true,
            code: true,
            name: true,
            locationType: true
          }
        }
      },
      orderBy: [{ name: "asc" }]
    })
  ]);

  return NextResponse.json({
    data: {
      washing_places: washingPlaces.map((item) => ({
        id: item.id.toString(),
        code: item.code,
        name: item.name
      })),
      grades: grades.map((item) => ({
        id: item.id.toString(),
        code: item.code,
        name: item.name
      })),
      warehouses: warehouses.map((warehouse) => ({
        id: warehouse.id.toString(),
        code: warehouse.code,
        name: warehouse.name,
        locations: warehouse.locations.map((location) => ({
          id: location.id.toString(),
          code: location.code,
          name: location.name,
          location_type: location.locationType
        }))
      }))
    }
  });
}
