import type { MothershipAddressCandidate } from "@/modules/address/types";
import type { HostPublicAddressDraft } from "@/modules/host/types";
import type { QuoteRequestBody } from "@/lib/frontend/types";

function draftPlaceId(draft: HostPublicAddressDraft): string {
  const street = draft.street.trim();
  const city = draft.city.trim();
  const state = draft.state.trim();
  return `draft_${street}_${city}_${state}`.replace(/\s+/g, "_").slice(0, 64);
}

function draftAddress(draft: HostPublicAddressDraft): QuoteRequestBody["pickup_address"] {
  const street = draft.street.trim();
  const city = draft.city.trim();
  const state = draft.state.trim();
  const zip = draft.zip?.trim() ?? "";
  return {
    street,
    city,
    state,
    zip,
    place_id: draftPlaceId(draft),
    formatted_address: `${street}, ${city}, ${state}${zip ? ` ${zip}` : ""}`,
    selected_from_suggestions: true,
  };
}

/** 用户确认的 MotherShip 候选 → 询价地址 */
export function applyHostCandidate(
  draft: HostPublicAddressDraft,
  candidate: MothershipAddressCandidate,
): QuoteRequestBody["pickup_address"] {
  return {
    ...draftAddress(draft),
    street: candidate.street,
    city: candidate.city,
    state: candidate.state,
    zip: candidate.zip || draft.zip?.trim() || "",
    formatted_address: candidate.formatted_address,
    mothership_option_id: candidate.option_id,
    mothership_display_label: candidate.display_label,
    selected_from_mothership: true,
  };
}
