import { NextResponse } from "next/server";

import { serializeLotDetail } from "@/features/lots/lib/serialize-lot";
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 { searchParams } = new URL(request.url);
  const rawCode = searchParams.get("code")?.trim();
  if (!rawCode) {
    return NextResponse.json(
      {
        message: "Validasi gagal",
        errors: { code: ["Kode scan wajib diisi"] }
      },
      { status: 422 }
    );
  }

  const code = rawCode.toUpperCase();
  const lot = await prisma.inventoryLot.findFirst({
    where: {
      OR: [
        { lotCode: code },
        { qrCodeValue: code },
        { barcodeValue: code }
      ]
    },
    include: {
      grade: true,
      unit: true,
      warehouse: true,
      warehouseLocation: true,
      purchase: {
        select: {
          id: true,
          purchaseNo: true,
          purchaseDate: true,
          agent: {
            select: {
              id: true,
              name: true
            }
          },
          buyoutSourceAgent: {
            select: {
              id: true,
              name: true
            }
          }
        }
      },
      purchaseLine: {
        select: {
          unitPrice: true,
          buyoutMalUnitPriceSnapshot: true,
          buyoutAgentSharePercent: true,
          buyoutProfitAmount: true,
          buyoutAgentCommission: true
        }
      },
      receipt: { select: { id: true, receiptNo: true, receiptDate: true } },
      parentLot: { select: { id: true, lotCode: true } },
      childLots: {
        select: {
          id: true,
          lotCode: true,
          status: true,
          availableQty: true,
          sourceType: true
        }
      },
      transformationOutputs: {
        include: {
          transformation: {
            include: {
              inputs: {
                include: {
                  sourceLot: {
                    select: {
                      id: true,
                      lotCode: true,
                      grade: { select: { name: true } }
                    }
                  }
                }
              },
              outputs: {
                include: {
                  resultLot: {
                    select: {
                      id: true,
                      lotCode: true,
                      availableQty: true,
                      unitCost: true,
                      status: true,
                      grade: { select: { name: true } }
                    }
                  }
                }
              }
            }
          }
        }
      },
      transformationInputs: {
        include: {
          transformation: {
            include: {
              inputs: {
                include: {
                  sourceLot: {
                    select: {
                      id: true,
                      lotCode: true,
                      grade: { select: { name: true } }
                    }
                  }
                }
              },
              outputs: {
                include: {
                  resultLot: {
                    select: {
                      id: true,
                      lotCode: true,
                      availableQty: true,
                      unitCost: true,
                      status: true,
                      grade: { select: { name: true } }
                    }
                  }
                }
              }
            }
          }
        }
      },
      consignmentLines: {
        include: {
          consignment: {
            include: {
              sales: { select: { name: true } },
              buyer: { select: { name: true } }
            }
          }
        },
        orderBy: [{ createdAt: "desc" }]
      }
    }
  });

  if (!lot) {
    return NextResponse.json({ message: "Lot tidak ditemukan" }, { status: 404 });
  }

  const availableQty = lot.availableQty.toNumber();
  const originalQty = lot.originalQty.toNumber();
  const damagedQty = lot.damagedQty.toNumber();
  const shrinkageQty = lot.shrinkageQty.toNumber();
  const reservedQty = lot.reservedQty.toNumber();
  const estimatedValue = Number((availableQty * lot.unitCost.toNumber()).toFixed(2));
  const movementCount = lot.transformationInputs.length + lot.transformationOutputs.length;
  const sourcePartyName = lot.purchase?.agent?.name ?? "Pembelian bebas";
  const gradeName = lot.grade?.name ?? null;

  return NextResponse.json({
    data: {
      summary_card: {
        lot_code: lot.lotCode,
        source_type: lot.sourceType,
        status: lot.status,
        grade: gradeName,
        supplier_name: sourcePartyName,
        warehouse_name: lot.warehouse.name,
        warehouse_location_name: lot.warehouseLocation?.name ?? null,
        available_qty: availableQty,
        original_qty: originalQty,
        reserved_qty: reservedQty,
        damaged_qty: damagedQty,
        shrinkage_qty: shrinkageQty,
        unit_code: lot.unit.code,
        unit_cost: lot.unitCost.toNumber(),
        estimated_value: estimatedValue,
        purchase_no: lot.purchase?.purchaseNo ?? null,
        purchase_date: lot.purchase?.purchaseDate.toISOString() ?? null,
        receipt_no: lot.receipt?.receiptNo ?? null,
        receipt_date: lot.receipt?.receiptDate.toISOString() ?? null,
        received_at: lot.receivedAt.toISOString(),
        qr_code_value: lot.qrCodeValue,
        barcode_value: lot.barcodeValue,
        parent_lot_code: lot.parentLot?.lotCode ?? null,
        child_lot_count: lot.childLots.length,
        transformation_count: movementCount
      },
      lot: serializeLotDetail(lot),
      procurement: {
        supplier_name: sourcePartyName,
        purchase_no: lot.purchase?.purchaseNo ?? null,
        purchase_date: lot.purchase?.purchaseDate.toISOString() ?? null,
        receipt_no: lot.receipt?.receiptNo ?? null,
        receipt_date: lot.receipt?.receiptDate.toISOString() ?? null,
        received_at: lot.receivedAt.toISOString(),
        source_type: lot.sourceType
      },
      mobile_actions: {
        can_mix: auth.user.role === "QC" || auth.user.role === "WAREHOUSE" || auth.user.role === "OWNER" || auth.user.role === "ADMIN" || auth.user.role === "SYSTEM_ADMIN",
        can_regrade: auth.user.role === "QC" || auth.user.role === "WAREHOUSE" || auth.user.role === "OWNER" || auth.user.role === "ADMIN" || auth.user.role === "SYSTEM_ADMIN",
        can_adjust: auth.user.role === "QC" || auth.user.role === "WAREHOUSE" || auth.user.role === "OWNER" || auth.user.role === "ADMIN" || auth.user.role === "SYSTEM_ADMIN"
      }
    }
  });
}
