import type { StockAdjustmentListItem } from "@/types/stock-adjustment";

type DecimalLike = { toNumber(): number };

type SerializableStockAdjustment = {
  id: bigint;
  adjustmentNo: string;
  adjustmentDate: Date;
  qtyChange: DecimalLike;
  availableQtyBefore: DecimalLike;
  availableQtyAfter: DecimalLike;
  notes: string | null;
  lot: {
    id: bigint;
    lotCode: string;
    grade: { name: string } | null;
    unit: { code: string };
  };
  adjustmentReason: {
    id: bigint;
    code: string;
    name: string;
    description: string | null;
    category: StockAdjustmentListItem["reason"]["category"];
  };
  createdBy: {
    id: bigint;
    name: string;
    role: { code: string };
  };
};

export function serializeStockAdjustment(
  item: SerializableStockAdjustment
): StockAdjustmentListItem {
  return {
    id: item.id.toString(),
    adjustment_no: item.adjustmentNo,
    adjustment_date: item.adjustmentDate.toISOString(),
    lot: {
      id: item.lot.id.toString(),
      lot_code: item.lot.lotCode,
      grade: item.lot.grade?.name ?? "-",
      unit_code: item.lot.unit.code
    },
    reason: {
      id: item.adjustmentReason.id.toString(),
      code: item.adjustmentReason.code,
      name: item.adjustmentReason.name,
      description: item.adjustmentReason.description,
      category: item.adjustmentReason.category
    },
    qty_change: item.qtyChange.toNumber(),
    available_qty_before: item.availableQtyBefore.toNumber(),
    available_qty_after: item.availableQtyAfter.toNumber(),
    created_by: {
      id: item.createdBy.id.toString(),
      name: item.createdBy.name,
      role: item.createdBy.role.code
    },
    notes: item.notes
  };
}
