import type { HubspotFormConfig } from "@/lib/hubspot";
import type { WpHubspotFormConnection } from "../types";
import { u } from "./shared";

export function mapHubspotFormConfig(
  connection?: WpHubspotFormConnection | null,
  legacyFormGuid?: string | null,
): HubspotFormConfig | undefined {
  const node = connection?.nodes?.[0];
  const fiche = node?.ficheFormulaireHubspot;
  const formGuid = u(fiche?.formGuid) ?? u(legacyFormGuid);
  const fields = (fiche?.champs ?? [])
    .map((field) => ({
      localKey: u(field?.cleLocale) ?? "",
      name: u(field?.nomInterne) ?? "",
      objectTypeId: u(field?.objectTypeId),
      active: field?.actif ?? undefined,
      required: field?.requis ?? undefined,
    }))
    .filter((field) => field.localKey && field.name);

  const config: HubspotFormConfig = {
    code: u(fiche?.code) ?? u(node?.slug),
    portalId: u(fiche?.portalId),
    formGuid,
    mode: u(fiche?.mode),
    fields: fields.length ? fields : undefined,
  };

  if (!config.code && !config.portalId && !config.formGuid && !config.mode && !config.fields) {
    return undefined;
  }

  return config;
}
