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 [purchases, warehouses] = await Promise.all([
    prisma.purchase.findMany({
      where: {
        purchaseType: "REGULAR",
        status: "SUBMITTED",
        receipts: {
          none: {}
        }
      },
      include: {
        agent: {
          select: {
            id: true,
            name: true
          }
        },
        lines: {
          include: {
            grade: {
              select: {
                id: true,
                code: true,
                name: true
              }
            },
            unit: {
              select: {
                id: true,
                code: true
              }
            },
            warehouse: {
              select: {
                id: true,
                name: true
              }
            },
            warehouseLocation: {
              select: {
                id: true,
                name: true
              }
            }
          }
        }
      },
      orderBy: [{ purchaseDate: "desc" }, { createdAt: "desc" }]
    }),
    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: {
      purchases: purchases.map((purchase) => ({
        id: purchase.id.toString(),
        purchase_no: purchase.purchaseNo,
        purchase_date: purchase.purchaseDate.toISOString().slice(0, 10),
        received_at: purchase.receivedAt?.toISOString() ?? null,
        supplier_name: purchase.agent?.name ?? "Pembelian bebas",
        notes: purchase.notes,
        lines: purchase.lines.map((line) => ({
          id: line.id.toString(),
          purchase_line_id: line.id.toString(),
          grade: line.grade
            ? {
                id: line.grade.id.toString(),
                code: line.grade.code,
                name: line.grade.name
              }
            : null,
          unit: {
            id: line.unit.id.toString(),
            code: line.unit.code
          },
          qty_ordered: line.qtyOrdered.toNumber(),
          qty_received: line.qtyReceived.toNumber(),
          qty_accepted: line.qtyAccepted.toNumber(),
          qty_rejected: line.qtyRejected.toNumber(),
          unit_cost: line.unitCost.toNumber(),
          warehouse_id: line.warehouse?.id?.toString() ?? null,
          warehouse_location_id: line.warehouseLocation?.id?.toString() ?? null
        }))
      })),
      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
        }))
      }))
    }
  });
}
