import { NextResponse } from "next/server";

import { serializeLotDetail } from "@/features/lots/lib/serialize-lot";
import { requireApiAccess } from "@/lib/authorization";
import { prisma } from "@/lib/prisma";

type RouteContext = { params: Promise<{ id: string }> };
const parseId = (id: string) => {
  try {
    return BigInt(id);
  } catch {
    return null;
  }
};

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

  const parsedId = parseId((await context.params).id);
  if (parsedId === null) {
    return NextResponse.json({ message: "Invalid id" }, { status: 400 });
  }

  const lot = await prisma.inventoryLot.findUnique({
    where: { id: parsedId },
    include: {
      grade: true,
      warehouse: true,
      warehouseLocation: true,
      unit: 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 not found" }, { status: 404 });
  }

  return NextResponse.json({
    data: serializeLotDetail(lot)
  });
}
