import type { WashingListItem } from "@/types/washing";

type DecimalLike = { toNumber(): number };

type WashingSerializable = {
  id: bigint;
  washingNo: string;
  status: string;
  startedAt: Date;
  expectedDoneAt: Date;
  completedAt: Date | null;
  washingCost: DecimalLike;
  durationHours: number;
  receiptFileUrl: string | null;
  beforeQty: DecimalLike;
  afterQty: DecimalLike | null;
  shrinkageQty: DecimalLike | null;
  beforeGradeName: string | null;
  afterGradeName: string | null;
  beforeWarehouseName: string;
  beforeLocationName: string | null;
  afterWarehouseName: string | null;
  afterLocationName: string | null;
  lot: {
    id: bigint;
    lotCode: string;
    availableQty: DecimalLike;
    unit: { code: string };
    grade: { name: string } | null;
    warehouse: { name: string };
    warehouseLocation: { name: string } | null;
    purchase: {
      agent: {
        name: string;
      } | null;
    } | null;
  };
  washingPlace: {
    id: bigint;
    name: string;
  };
};

export function serializeWashing(item: WashingSerializable): WashingListItem {
  return {
    id: item.id.toString(),
    washing_no: item.washingNo,
    status: item.status,
    started_at: item.startedAt.toISOString(),
    expected_done_at: item.expectedDoneAt.toISOString(),
    completed_at: item.completedAt ? item.completedAt.toISOString() : null,
    washing_cost: item.washingCost.toNumber(),
    duration_hours: item.durationHours,
    receipt_file_url: item.receiptFileUrl,
    before_qty: item.beforeQty.toNumber(),
    after_qty: item.afterQty?.toNumber() ?? null,
    shrinkage_qty: item.shrinkageQty?.toNumber() ?? null,
    before_grade_name: item.beforeGradeName,
    after_grade_name: item.afterGradeName,
    before_warehouse_name: item.beforeWarehouseName,
    before_location_name: item.beforeLocationName,
    after_warehouse_name: item.afterWarehouseName,
    after_location_name: item.afterLocationName,
    lot: {
      id: item.lot.id.toString(),
      lot_code: item.lot.lotCode,
      supplier: item.lot.purchase?.agent?.name ?? "Pembelian bebas",
      grade_name: item.lot.grade?.name ?? null,
      available_qty: item.lot.availableQty.toNumber(),
      unit_code: item.lot.unit.code,
      warehouse_name: item.lot.warehouse.name,
      location_name: item.lot.warehouseLocation?.name ?? null
    },
    washing_place: {
      id: item.washingPlace.id.toString(),
      name: item.washingPlace.name
    }
  };
}
