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 [agents, lots] = await Promise.all([
    prisma.agent.findMany({
      where: {
        purchases: {
          some: {
            lots: {
              some: {
                status: "ACTIVE",
                availableQty: {
                  gt: 0
                }
              }
            }
          }
        }
      },
      orderBy: [{ name: "asc" }],
      select: {
        id: true,
        code: true,
        name: true
      }
    }),
    prisma.inventoryLot.findMany({
      where: {
        status: "ACTIVE",
        availableQty: {
          gt: 0
        },
        purchase: {
          agentId: {
            not: null
          },
          purchaseType: "REGULAR"
        }
      },
      orderBy: [{ receivedAt: "desc" }],
      include: {
        purchase: {
          select: {
            agentId: true,
            agent: {
              select: {
                name: true
              }
            },
            profitShareScheme: {
              select: {
                shareAgent: true
              }
            }
          }
        },
        purchaseLine: {
          select: {
            malUnitPrice: true
          }
        },
        grade: {
          select: {
            name: true
          }
        },
        unit: {
          select: {
            code: true
          }
        },
        warehouse: {
          select: {
            name: true
          }
        },
        warehouseLocation: {
          select: {
            name: true
          }
        }
      }
    })
  ]);

  return NextResponse.json({
    data: {
      agents: agents.map((agent) => ({
        id: agent.id.toString(),
        code: agent.code,
        name: agent.name
      })),
      lots: lots
        .filter((lot) => lot.purchase?.agentId && lot.purchase?.agent?.name)
        .map((lot) => ({
          id: lot.id.toString(),
          agent_id: lot.purchase!.agentId!.toString(),
          agent_name: lot.purchase!.agent!.name,
          lot_code: lot.lotCode,
          grade: lot.grade?.name ?? "-",
          available_qty: lot.availableQty.toNumber(),
          unit_code: lot.unit.code,
          mal_unit_price: lot.purchaseLine?.malUnitPrice?.toNumber() ?? 0,
          agent_share_percent: lot.purchase?.profitShareScheme?.shareAgent.toNumber() ?? 0,
          warehouse: lot.warehouse.name,
          location: lot.warehouseLocation?.name ?? null
        }))
    }
  });
}
