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 modulesByRole: Record<string, string[]> = {
    OWNER: [
      "dashboard",
      "lots",
      "washing",
      "stock_adjustments",
      "lot_transformations",
      "sales_regular",
      "sales_jit",
      "consignments",
      "purchases",
      "fund_requests",
      "purchase_analyses",
      "purchase_realizations"
    ],
    PURCHASING: [
      "dashboard",
      "purchases",
      "fund_requests",
      "purchase_analyses",
      "purchase_realizations"
    ],
    WAREHOUSE: [
      "dashboard",
      "lots",
      "washing",
      "stock_adjustments"
    ],
    QC: [
      "dashboard",
      "lots",
      "washing",
      "lot_transformations",
      "stock_adjustments"
    ],
    SALES: [
      "dashboard",
      "lots",
      "sales_regular",
      "sales_jit",
      "consignments"
    ],
    ADMIN: [
      "dashboard",
      "lots",
      "washing",
      "stock_adjustments",
      "lot_transformations",
      "sales_regular",
      "sales_jit",
      "consignments",
      "purchases",
      "fund_requests",
      "purchase_analyses",
      "purchase_realizations"
    ],
    SYSTEM_ADMIN: [
      "dashboard",
      "lots",
      "washing",
      "stock_adjustments",
      "lot_transformations",
      "sales_regular",
      "sales_jit",
      "consignments",
      "purchases",
      "fund_requests",
      "purchase_analyses",
      "purchase_realizations"
    ]
  };

  const [grades, warehouses, summary] = await Promise.all([
    prisma.grade.findMany({
      where: { status: "ACTIVE" },
      orderBy: [{ name: "asc" }],
      select: { id: true, code: true, name: true }
    }),
    prisma.warehouse.findMany({
      where: { status: "ACTIVE" },
      orderBy: [{ name: "asc" }],
      include: {
        locations: {
          where: { status: "ACTIVE" },
          orderBy: [{ name: "asc" }],
          select: { id: true, code: true, name: true, locationType: true }
        }
      }
    }),
    prisma.$transaction([
      prisma.inventoryLot.count({
        where: {
          status: "ACTIVE",
          availableQty: { gt: 0 }
        }
      }),
      prisma.purchase.count({
        where: {
          purchaseType: "REGULAR",
          status: "DRAFT"
        }
      }),
      prisma.purchase.count({
        where: {
          purchaseType: "REGULAR",
          status: "SUBMITTED"
        }
      }),
      prisma.regularSale.count({
        where: {
          status: "OPEN"
        }
      }),
      prisma.consignmentLine.count({
        where: {
          status: "OPEN"
        }
      }),
      prisma.lotWashing.count({
        where: {
          status: "IN_PROGRESS"
        }
      })
    ])
  ]);

  const [
    activeLotCount,
    draftPurchaseCount,
    submittedPurchaseCount,
    openRegularSaleCount,
    openConsignmentLineCount,
    inProgressWashingCount
  ] = summary;

  return NextResponse.json({
    data: {
      user: auth.user,
      modules: modulesByRole[auth.user.role] ?? ["dashboard"],
      summary: {
        active_lot_count: activeLotCount,
        draft_purchase_count: draftPurchaseCount,
        submitted_purchase_count: submittedPurchaseCount,
        open_regular_sale_count: openRegularSaleCount,
        open_consignment_line_count: openConsignmentLineCount,
        in_progress_washing_count: inProgressWashingCount
      },
      transformation_types: [
        { code: "MIX", label: "Mixing" },
        { code: "REGRADE", label: "Regrade" }
      ],
      remainder_modes: [
        { code: "KEEP_SOURCE_GRADE", label: "Simpan sisa di lot sumber" },
        { code: "SHRINKAGE", label: "Catat sebagai shrinkage" }
      ],
      processing_loss_modes: [
        { code: "SHRINKAGE", label: "Catat sebagai shrinkage" }
      ],
      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
        }))
      }))
    }
  });
}
