import { createFreshFlockTestAccount } from "@/lib/flock/fresh-account";
import { getFlockTestAccount, type FlockTestAccount } from "@/lib/flock/env";
import type {
  FlockQuoteInput,
  FlockRegistrationOverride,
} from "@/workers/rpa/flock/types";

export function hasFlockRegistrationOverride(
  reg: FlockRegistrationOverride | undefined,
): boolean {
  if (!reg) {
    return false;
  }
  return Boolean(
    reg.firstName?.trim() ||
      reg.lastName?.trim() ||
      reg.company?.trim() ||
      reg.email?.trim() ||
      reg.phone?.trim() ||
      reg.shipmentsPerMonth?.trim(),
  );
}

/** 用户自填注册信息与系统随机/环境默认合并 */
export function resolveFlockQuoteAccount(input: FlockQuoteInput): FlockTestAccount {
  const reg = input.registration;
  if (!hasFlockRegistrationOverride(reg)) {
    return getFlockTestAccount();
  }

  const fallback = createFreshFlockTestAccount();
  const merged: FlockTestAccount = {
    firstName: reg!.firstName?.trim() || fallback.firstName,
    lastName: reg!.lastName?.trim() || fallback.lastName,
    company: reg!.company?.trim() || fallback.company,
    email: reg!.email?.trim() || fallback.email,
    phone: reg!.phone?.trim() || fallback.phone,
    shipmentsPerMonth:
      reg!.shipmentsPerMonth?.trim() || fallback.shipmentsPerMonth,
  };

  console.log(
    `[flock-account] 使用用户指定注册信息 email=${merged.email} phone=${merged.phone}`,
  );
  return merged;
}
