import { randomUUID } from "node:crypto";
import { toAxelWholeInches, toAxelWholePounds } from "@/modules/quote/unit-converter";

export type AxelPlaceLocation = Record<string, unknown>;

export type AxelCargoInput = {
  palletCount: number;
  weightLb: number;
  lengthIn: number;
  widthIn: number;
  heightIn: number;
};

function buildAutocompleteResult(
  description: string,
  placeId: string,
): Record<string, unknown> {
  const parts = description.split(",").map((p) => p.trim());
  return {
    description,
    mainText: parts[0] ?? description,
    placeId,
    secondaryText: parts.slice(1).join(", "),
    types: ["geocode"],
  };
}

export function enrichAxelLocation(
  raw: AxelPlaceLocation,
  description: string,
): AxelPlaceLocation {
  const placeId = String(raw.placeId ?? "");
  return {
    ...raw,
    placeId,
    autocompleteResult: buildAutocompleteResult(description, placeId),
    serviceStartTime: "12:00am",
    serviceEndTime: "11:59pm",
  };
}

export function buildAxelCargo(
  cargo: AxelCargoInput,
): Record<string, unknown> {
  const id = randomUUID();
  return {
    [id]: {
      length: toAxelWholeInches(cargo.lengthIn),
      width: toAxelWholeInches(cargo.widthIn),
      height: toAxelWholeInches(cargo.heightIn),
      quantity: cargo.palletCount,
      weight: toAxelWholePounds(cargo.weightLb),
      type: "Pallet",
    },
  };
}

export function buildPickupDateIso(date = new Date()): string {
  const pickupDate = new Date(date);
  pickupDate.setUTCHours(19, 0, 0, 0);
  return pickupDate.toISOString();
}

export function buildAxelShipmentPayload(input: {
  pickup: AxelPlaceLocation;
  delivery: AxelPlaceLocation;
  pickupDescription: string;
  deliveryDescription: string;
  cargo: AxelCargoInput;
  pickupDate?: Date;
}): Record<string, unknown> {
  return {
    pickupDate: buildPickupDateIso(input.pickupDate),
    pickupLocation: enrichAxelLocation(input.pickup, input.pickupDescription),
    deliveryLocation: enrichAxelLocation(
      input.delivery,
      input.deliveryDescription,
    ),
    cargo: buildAxelCargo(input.cargo),
  };
}
