import { NextResponse } from "next/server";

import { requireApiAccess } from "@/lib/authorization";
import { prisma } from "@/lib/prisma";
import { serializePurchaseAnalysisListItem } from "@/features/purchase-analysis/lib/serialize-purchase-analysis";

const analysisInclude = {
  agent: {
    select: {
      id: true,
      name: true
    }
  },
  profitShareScheme: {
    select: {
      shareAgent: true
    }
  },
  lines: {
    select: {
      subtotal: true,
      qtyOrdered: true,
      qtyReceived: true,
      qtyAccepted: true,
      unitPrice: true,
      malUnitPrice: true,
      moistureReceivedPercent: true,
      purchaseMoisturePercent: true,
      marketReferencePrice: true,
      unit: {
        select: {
          code: true
        }
      }
    }
  },
  lots: {
    select: {
      originalQty: true,
      finalMoisturePercent: true,
      aboveAverageRatioPercent: true,
      unit: {
        select: {
          code: true
        }
      }
    }
  },
  analysis: {
    include: {
      costEntries: true
    }
  }
} as const;

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

  try {
    const purchases = await prisma.purchase.findMany({
      where: {
        status: "SUBMITTED",
        purchaseType: "REGULAR"
      },
      select: {
        id: true,
        purchaseNo: true,
        purchaseDate: true,
        status: true,
        moistureBuyPercent: true,
        moistureReceivedPercent: true,
        aboveAverageRatioPercent: true,
        mkSharePercent: true,
        nonMkSharePercent: true,
        shippingCost: true,
        incomingOperationalCost: true,
        afterArrivalOperationalCost: true,
        agent: analysisInclude.agent,
        profitShareScheme: analysisInclude.profitShareScheme,
        lines: analysisInclude.lines,
        lots: analysisInclude.lots,
        analysis: analysisInclude.analysis
      },
      orderBy: [{ createdAt: "desc" }]
    });

    return NextResponse.json({
      data: purchases.map(serializePurchaseAnalysisListItem)
    });
  } catch (error) {
    console.error("Failed to load purchase analyses:", error);
    return NextResponse.json(
      { message: "Gagal memuat analisis pembelian" },
      { status: 500 }
    );
  }
}
