import { NextResponse } from "next/server";

import { serializeSales } from "@/features/sales/lib/serialize-sales";
import { requireApiAccess } from "@/lib/authorization";
import { prisma } from "@/lib/prisma";

type RouteContext = { params: Promise<{ id: string }> };

function 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 sales = await prisma.sales.findUnique({
    where: { id: parsedId },
    include: {
      bankAccounts: { include: { bank: true } },
      _count: {
        select: {
          consignments: true
        }
      }
    }
  });

  if (!sales) {
    return NextResponse.json({ message: "Sales not found" }, { status: 404 });
  }

  const [mutations, commissionCloseCount] = await Promise.all([
    prisma.salesCommissionMutation.findMany({
      where: { salesId: parsedId },
      orderBy: [{ occurredAt: "asc" }, { id: "asc" }]
    }),
    prisma.consignmentLine.count({
      where: {
        status: "CLOSED",
        salesCommission: { gt: 0 },
        consignment: {
          salesId: parsedId
        }
      }
    })
  ]);

  return NextResponse.json({
    data: {
      ...serializeSales(sales),
      stats: {
        consignment_count: sales._count.consignments,
        commission_close_count: commissionCloseCount,
        history_count: mutations.length
      },
      commission_history: mutations.map((item) => ({
        id: item.id.toString(),
        source: item.source as "OPENING_BALANCE" | "MANUAL_ADJUSTMENT" | "CONSIGNMENT_COMMISSION",
        direction: item.direction as "IN" | "OUT",
        amount: item.amount.toNumber(),
        balance_after: item.balanceAfter.toNumber(),
        occurred_at: item.occurredAt.toISOString(),
        effective_date: item.effectiveDate?.toISOString().slice(0, 10) ?? null,
        reference_no: item.referenceNo,
        description:
          item.notes ??
          (item.source === "CONSIGNMENT_COMMISSION"
            ? "Komisi sales dari titip jual"
            : item.source === "MANUAL_ADJUSTMENT"
              ? "Penyesuaian manual komisi sales"
              : "Saldo pembuka komisi sales"),
        notes: item.referenceType
          ? `${item.referenceType}${item.referenceId ? ` · ${item.referenceId}` : ""}`
          : null
      }))
    }
  });
}
