import type { ReceiptDetail, ReceiptListItem } from "@/types/receipt";

type DecimalLike = { toNumber(): number };

type ReceiptListSerializable = {
  id: bigint;
  receiptNo: string;
  receiptDate: Date;
  status: string;
  purchase: { id: bigint; purchaseNo: string };
  lines: Array<unknown>;
  lots: Array<unknown>;
};

type ReceiptDetailSerializable = {
  id: bigint;
  receiptNo: string;
  receiptDate: Date;
  status: string;
  notes: string | null;
  purchase: { id: bigint; purchaseNo: string };
  lines: Array<{
    id: bigint;
    purchaseLineId: bigint;
    qtyReceived: DecimalLike;
    qtyAccepted: DecimalLike;
    qtyRejected: DecimalLike;
    unitCost: DecimalLike;
    notes: string | null;
    grade: { id: bigint; name: string } | null;
    unit: { id: bigint; code: string };
    warehouse: { id: bigint; name: string };
    warehouseLocation: { id: bigint; name: string } | null;
  }>;
  lots: Array<{
    id: bigint;
    lotCode: string;
    status: string;
  }>;
};

export function serializeReceiptListItem(receipt: ReceiptListSerializable): ReceiptListItem {
  return {
    id: receipt.id.toString(),
    receipt_no: receipt.receiptNo,
    purchase: {
      id: receipt.purchase.id.toString(),
      purchase_no: receipt.purchase.purchaseNo
    },
    receipt_date: receipt.receiptDate.toISOString().slice(0, 10),
    status: receipt.status,
    line_count: receipt.lines.length,
    lot_count: receipt.lots.length
  };
}

export function serializeReceiptDetail(receipt: ReceiptDetailSerializable): ReceiptDetail {
  return {
    id: receipt.id.toString(),
    receipt_no: receipt.receiptNo,
    purchase: {
      id: receipt.purchase.id.toString(),
      purchase_no: receipt.purchase.purchaseNo
    },
    receipt_date: receipt.receiptDate.toISOString().slice(0, 10),
    status: receipt.status,
    notes: receipt.notes,
    lines: receipt.lines.map((line) => ({
      id: line.id.toString(),
      purchase_line_id: line.purchaseLineId.toString(),
      grade: line.grade
        ? { id: line.grade.id.toString(), name: line.grade.name }
        : null,
      qty_received: line.qtyReceived.toNumber(),
      qty_accepted: line.qtyAccepted.toNumber(),
      qty_rejected: line.qtyRejected.toNumber(),
      unit: { id: line.unit.id.toString(), code: line.unit.code },
      unit_cost: line.unitCost.toNumber(),
      warehouse: { id: line.warehouse.id.toString(), name: line.warehouse.name },
      location: line.warehouseLocation
        ? { id: line.warehouseLocation.id.toString(), name: line.warehouseLocation.name }
        : null,
      notes: line.notes
    })),
    generated_lots: receipt.lots.map((lot) => ({
      id: lot.id.toString(),
      lot_code: lot.lotCode,
      status: lot.status
    }))
  };
}
