import type { GradeRecord } from "@/types/master-data";

type PriceStandardValue = { toNumber(): number };

type SerializableGrade = {
  id: bigint;
  code: string;
  legacyCode: string | null;
  isMangkok: boolean;
  name: string;
  description: string | null;
  status: string;
  createdAt: Date;
  updatedAt: Date;
  buyPriceStandards: Array<{
    id: bigint;
    startDate: Date;
    endDate: Date | null;
    minPrice: PriceStandardValue;
    maxPrice: PriceStandardValue;
    notes: string | null;
  }>;
  sellPriceStandards: Array<{
    id: bigint;
    startDate: Date;
    endDate: Date | null;
    minPrice: PriceStandardValue;
    maxPrice: PriceStandardValue;
    notes: string | null;
  }>;
};

function serializePriceStandard(item: SerializableGrade["buyPriceStandards"][number]) {
  return {
    id: item.id.toString(),
    start_date: item.startDate.toISOString().slice(0, 10),
    end_date: item.endDate ? item.endDate.toISOString().slice(0, 10) : null,
    min_price: item.minPrice.toNumber(),
    max_price: item.maxPrice.toNumber(),
    notes: item.notes
  };
}

export function serializeGrade(grade: SerializableGrade): GradeRecord {
  return {
    id: grade.id.toString(),
    code: grade.code,
    legacy_code: grade.legacyCode,
    is_mangkok: grade.isMangkok,
    name: grade.name,
    description: grade.description,
    status: grade.status,
    buy_price_standards: grade.buyPriceStandards.map(serializePriceStandard),
    sell_price_standards: grade.sellPriceStandards.map(serializePriceStandard),
    created_at: grade.createdAt.toISOString(),
    updated_at: grade.updatedAt.toISOString()
  };
}

