import { listMockMothershipCandidates } from "@/modules/address/candidate-catalog";
import {
  loadAddressCandidatesCache,
  saveAddressCandidatesCache,
} from "@/modules/address/candidates-cache";
import type {
  AddressLookupInput,
  MothershipCandidatesResult,
} from "@/modules/address/types";
import { resolveAxelMothershipCandidates } from "@/lib/axel/candidates";
import { isRpaMockMode } from "@/lib/rpa/selectors";

function requiresSelection(
  pickup: MothershipCandidatesResult["pickup_candidates"],
  delivery: MothershipCandidatesResult["delivery_candidates"],
): boolean {
  return pickup.length > 1 || delivery.length > 1;
}

/**
 * 拉取 MotherShip 地址联想候选项；多选时禁止自动择一，须由用户确认后再询价。
 * RPA_MOCK_MODE=true 时仅用本地 catalog；否则必须走真实 RPA 列表抓取。
 */
export async function resolveMothershipCandidates(input: {
  pickup: AddressLookupInput;
  delivery: AddressLookupInput;
}): Promise<MothershipCandidatesResult> {
  if (process.env.RPA_MOCK_MODE === "true" || isRpaMockMode()) {
    const pickup_candidates = listMockMothershipCandidates(input.pickup);
    const delivery_candidates = listMockMothershipCandidates(input.delivery);
    return {
      pickup_candidates,
      delivery_candidates,
      requires_selection: requiresSelection(
        pickup_candidates,
        delivery_candidates,
      ),
    };
  }

  const cached = await loadAddressCandidatesCache(input);
  if (cached) {
    return {
      pickup_candidates: cached.pickup_candidates,
      delivery_candidates: cached.delivery_candidates,
      requires_selection: requiresSelection(
        cached.pickup_candidates,
        cached.delivery_candidates,
      ),
    };
  }

  const { pickup_candidates, delivery_candidates } =
    await resolveAxelMothershipCandidates(input);

  await saveAddressCandidatesCache(input, {
    pickup_candidates,
    delivery_candidates,
  });

  return {
    pickup_candidates,
    delivery_candidates,
    requires_selection: requiresSelection(
      pickup_candidates,
      delivery_candidates,
    ),
  };
}
