











import { createPortfolioIssueIdentityHash } from "./xombeztlyiegtybxtzkg.mjs";

const ALLIANZ_POLICY_LIST_RESOURCE_URL = "https://chuck.allianz.pl/web/guest/polisy"
  + "?p_p_id=policylist_WAR_policylist&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view"
  + "&p_p_resource_id=policyList&p_p_cacheability=cacheLevelPage";
const ALLIANZ_POLICY_DETAIL_RESOURCE_URL = "https://chuck.allianz.pl/web/guest/polisy"
  + "?p_p_id=policylist_WAR_policylist&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view"
  + "&p_p_resource_id=showPolicyDetail&p_p_cacheability=cacheLevelPage";
const ALLIANZ_POLICY_CLIENTS_RESOURCE_URL = "https://chuck.allianz.pl/web/guest/polisy"
  + "?p_p_id=policylist_WAR_policylist&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view"
  + "&p_p_resource_id=policyClientsList&p_p_cacheability=cacheLevelPage";
const ALLIANZ_PARAM_PREFIX = "_policylist_WAR_policylist_";
const ALLIANZ_API_PAGE_SIZE = 100;
const ALLIANZ_API_MAX_PAGES = 400;

const ALLIANZ_LIST_COLUMNS = [
  "clientProprietary",
  "policyStartDate",
  "expiryPolicyDate",
  "claimExists",
  "policyOwnersName",
  "lob",
  "policyName.policyUnit",
  "policyName.policyYear",
  "policyName.policyRiskCode",
  "policyName.policyNumber",
  "applicationNumber",
  "policyStatus",
  "serviceAgentNumber",
  "sellerAgentNumber",
  "insuranceName",
];
const ALLIANZ_DATE_COLUMNS = new Set(["policyStartDate", "expiryPolicyDate"]);
const ALLIANZ_CLIENT_COLUMNS = [
  "clientProprietary",
  "active",
  "startDate",
  "endDate",
  "clientType",
  "clientPolicyRole",
  "clientFullname",
  "clientIdentifier",
  "nip",
  "pgzInsuranceAmount",
  "pgzPolicyGroup",
  "pgzCertificate",
];
const ALLIANZ_CONTEXT_PROPERTY = "allianzPortfolioContext";

export const ALLIANZ_PORTFOLIO_COMPLETENESS_ERROR = "PORTFOLIO_COMPLETENESS_FAILED";

function throwAllianzCompletenessError(reason) {
  const error = new Error(`Import Allianz przerwany: lista polis wróciła niekompletna (${reason}).`);
  error.code = ALLIANZ_PORTFOLIO_COMPLETENESS_ERROR;
  error.reason = reason;
  throw error;
}

function compactText(value) {
  return String(value ?? "").replace(/\s+/g, " ").trim();
}

function getAllianzSourceIdentity(item) {
  const sourceId = compactText(item?.id);
  if (sourceId) return `id:${sourceId}`;
  const policyNumber = compactText(item?.policyName?.policyNumber)
    .replace(/[^0-9A-Za-z]/g, "")
    .toUpperCase();
  if (!policyNumber) return "";
  return [
    "period",
    policyNumber,
    formatAllianzEpochDate(item?.policyStartDate),
    formatAllianzEpochDate(item?.policyEndDate ?? item?.expiryPolicyDate),
  ].join("\0");
}

function addAllianzPageSourceIdentities(items, identitiesFromEarlierPages) {
  const identitiesFromCurrentPage = new Set();
  for (const item of Array.isArray(items) ? items : []) {
    const identity = getAllianzSourceIdentity(item);
    
    
    if (!identity) continue;
    if (identitiesFromEarlierPages.has(identity)) {
      throwAllianzCompletenessError("repeated_item_across_pages");
    }
    identitiesFromCurrentPage.add(identity);
  }
  for (const identity of identitiesFromCurrentPage) {
    identitiesFromEarlierPages.add(identity);
  }
}

 
export function buildAllianzPolicyListBody({ displayStart = 0, displayLength = ALLIANZ_API_PAGE_SIZE, echo = 1 } = {}) {
  const params = new URLSearchParams();
  const set = (name, value) => params.set(`${ALLIANZ_PARAM_PREFIX}${name}`, String(value));
  set("sEcho", echo);
  set("iColumns", ALLIANZ_LIST_COLUMNS.length);
  set("sColumns", "");
  set("iDisplayStart", displayStart);
  set("iDisplayLength", displayLength);
  ALLIANZ_LIST_COLUMNS.forEach((column, index) => set(`mDataProp_${index}`, column));
  set("iSortingCols", 0);
  ALLIANZ_LIST_COLUMNS.forEach((column, index) => set(`bSortable_${index}`, "true"));
  ALLIANZ_LIST_COLUMNS.forEach((column, index) => set(`mDataType_${index}`, ALLIANZ_DATE_COLUMNS.has(column) ? "Date" : ""));
  set("policyFilter", "ALL");
  return params.toString();
}

async function fetchAllianzPolicyListPage(page, { displayStart, echo }) {
  const body = buildAllianzPolicyListBody({ displayStart, displayLength: ALLIANZ_API_PAGE_SIZE, echo });
  return page.evaluate(async ({ url, payload }) => {
    
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 45000);
    try {
      const response = await fetch(url, {
        method: "POST",
        credentials: "include",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
          Accept: "application/json, text/javascript, */*; q=0.01",
          "X-Requested-With": "XMLHttpRequest",
        },
        body: payload,
        signal: controller.signal,
      });
      if (!response.ok) return { ok: false, status: response.status, items: [], total: Number.NaN };
      const data = await response.json().catch(() => null);
      const resultSet = data?.resultSet;
      if (!resultSet || typeof resultSet !== "object" || !Array.isArray(resultSet.aaData)) {
        return { ok: false, status: response.status, items: [], total: Number.NaN };
      }
      return {
        ok: true,
        status: response.status,
        items: resultSet.aaData,
        total: Number(resultSet.iTotalRecords),
      };
    } catch (error) {
      return { ok: false, status: 0, items: [], total: Number.NaN, error: String((error && error.message) || error) };
    } finally {
      clearTimeout(timer);
    }
  }, { url: ALLIANZ_POLICY_LIST_RESOURCE_URL, payload: body });
}

 
export async function fetchAllianzPolicies(page, { onProgress = () => {} } = {}) {
  const first = await fetchAllianzPolicyListPage(page, { displayStart: 0, echo: 1 });
  if (!first.ok) {
    console.error(`Import Allianz: policyList odpowiedziało błędem (status ${first.status || "sieciowy"}${first.error ? `: ${first.error}` : ""}).`);
    throw new Error("Nie udało się pobrać listy polis z Allianz. Spróbuj ponownie za chwilę.");
  }
  const total = Number(first.total);
  if (!Number.isSafeInteger(total) || total < 0) throwAllianzCompletenessError("no_total");
  const pageQuantity = Math.max(1, Math.ceil(total / ALLIANZ_API_PAGE_SIZE));
  if (pageQuantity > ALLIANZ_API_MAX_PAGES) throwAllianzCompletenessError("page_limit");
  if (first.items.length !== Math.min(ALLIANZ_API_PAGE_SIZE, total)) throwAllianzCompletenessError("short_page");
  const items = [...first.items];
  const sourceIdentities = new Set();
  addAllianzPageSourceIdentities(first.items, sourceIdentities);
  onProgress({ collected: items.length, total, page: 1, pageQuantity });
  for (let pageNumber = 2; pageNumber <= pageQuantity; pageNumber += 1) {
    const slice = await fetchAllianzPolicyListPage(page, {
      displayStart: (pageNumber - 1) * ALLIANZ_API_PAGE_SIZE,
      echo: pageNumber,
    });
    if (!slice.ok) {
      console.error(`Import Allianz: pobieranie przerwane na stronie ${pageNumber} (status ${slice.status || "sieciowy"}).`);
      throw new Error("Pobieranie polis z Allianz zostało przerwane. Spróbuj ponownie za chwilę.");
    }
    if (Number(slice.total) !== total) throwAllianzCompletenessError("total_changed");
    const expectedCount = Math.min(ALLIANZ_API_PAGE_SIZE, Math.max(0, total - ((pageNumber - 1) * ALLIANZ_API_PAGE_SIZE)));
    if (slice.items.length !== expectedCount) throwAllianzCompletenessError("short_page");
    addAllianzPageSourceIdentities(slice.items, sourceIdentities);
    items.push(...slice.items);
    onProgress({ collected: items.length, total, page: pageNumber, pageQuantity });
  }
  if (items.length !== total) throwAllianzCompletenessError("count_mismatch");
  return items;
}

function getAllianzPolicyPeriodKey(item) {
  const policyNumber = compactText(item?.policyName?.policyNumber)
    .replace(/[^0-9A-Za-z]/g, "")
    .toUpperCase();
  if (!policyNumber) return "";
  return [
    policyNumber,
    formatAllianzEpochDate(item?.policyStartDate),
    formatAllianzEpochDate(item?.policyEndDate ?? item?.expiryPolicyDate),
  ].join("\0");
}

function getAllianzPolicySource(item) {
  const id = compactText(item?.id);
  const system = compactText(item?.policySourceSystem);
  const hashToCompare = compactText(item?.hashToCompare);
  return id && system
    ? { id, system, hashToCompare }
    : null;
}

function setAllianzPolicyContext(item, context) {
  if (!item || typeof item !== "object") return;
  Object.defineProperty(item, ALLIANZ_CONTEXT_PROPERTY, {
    configurable: true,
    enumerable: false,
    writable: true,
    value: context,
  });
}

async function fetchAllianzPolicyContext(page, source) {
  return page.evaluate(async ({
    clientColumns,
    clientsUrl,
    detailUrl,
    namespace,
    policySource,
  }) => {
    const fetchJson = async (url, params) => {
      const requestUrl = new URL(url);
      for (const [name, value] of params) requestUrl.searchParams.set(name, String(value ?? ""));
      const controller = new AbortController();
      const timer = setTimeout(() => controller.abort(), 30_000);
      try {
        const response = await fetch(requestUrl, {
          credentials: "include",
          headers: {
            Accept: "application/json, text/javascript, */*; q=0.01",
            "X-Requested-With": "XMLHttpRequest",
          },
          signal: controller.signal,
        });
        if (!response.ok) return null;
        const payload = await response.json().catch(() => null);
        return payload?.resultSet && typeof payload.resultSet === "object"
          ? payload.resultSet
          : null;
      } catch {
        return null;
      } finally {
        clearTimeout(timer);
      }
    };
    const shared = [
      [`${namespace}policy_id`, policySource.id],
      [`${namespace}system`, policySource.system],
      [`${namespace}hashToCompare`, policySource.hashToCompare],
    ];
    const clientParams = [
      [`${namespace}sEcho`, 1],
      [`${namespace}iColumns`, clientColumns.length],
      [`${namespace}sColumns`, ""],
      [`${namespace}iDisplayStart`, 0],
      [`${namespace}iDisplayLength`, 100],
      ...clientColumns.flatMap((column, index) => [
        [`${namespace}mDataProp_${index}`, column],
        [`${namespace}bSortable_${index}`, "true"],
      ]),
      ...shared,
    ];
    const [detail, clientsResult] = await Promise.all([
      fetchJson(detailUrl, shared),
      fetchJson(clientsUrl, clientParams),
    ]);
    return {
      detail,
      clients: Array.isArray(clientsResult?.aaData) ? clientsResult.aaData : [],
    };
  }, {
    clientColumns: ALLIANZ_CLIENT_COLUMNS,
    clientsUrl: ALLIANZ_POLICY_CLIENTS_RESOURCE_URL,
    detailUrl: ALLIANZ_POLICY_DETAIL_RESOURCE_URL,
    namespace: ALLIANZ_PARAM_PREFIX,
    policySource: source,
  });
}

 
export async function enrichAllianzPolicyItems(page, items, {
  onProgress = () => {},
} = {}) {
  const groups = new Map();
  for (const item of Array.isArray(items) ? items : []) {
    const key = getAllianzPolicyPeriodKey(item);
    if (!key) continue;
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(item);
  }
  let processed = 0;
  for (const groupItems of groups.values()) {
    const representative = groupItems.find((item) => getAllianzPolicySource(item));
    const source = getAllianzPolicySource(representative);
    if (source) {
      const context = await fetchAllianzPolicyContext(page, source).catch(() => null);
      if (context) {
        for (const item of groupItems) setAllianzPolicyContext(item, context);
      }
    }
    processed += 1;
    onProgress({ processed, total: groups.size });
  }
  return items;
}

 
export function formatAllianzEpochDate(value) {
  const text = compactText(value);
  const iso = /^(\d{4})-(\d{2})-(\d{2})(?:T|\s|$)/.exec(text);
  if (iso) return `${iso[1]}-${iso[2]}-${iso[3]}`;
  const wrappedEpoch = /^\/Date\((\d+)(?:[+-]\d{4})?\)\/$/.exec(text);
  const epoch = Number(wrappedEpoch ? wrappedEpoch[1] : value);
  if (!Number.isFinite(epoch) || epoch <= 0) return "";
  const date = new Date(epoch);
  if (!Number.isFinite(date.getTime())) return "";
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${date.getFullYear()}-${month}-${day}`;
}

export function getAllianzPortfolioMinEndDate(referenceDate = new Date()) {
  const cutoff = referenceDate instanceof Date
    ? new Date(referenceDate.getTime())
    : new Date(referenceDate);
  if (!Number.isFinite(cutoff.getTime())) return "";
  cutoff.setFullYear(cutoff.getFullYear() - 1);
  return formatAllianzEpochDate(cutoff.getTime());
}

function getAllianzIssueDate(item) {
  for (const candidate of [
    item?.issueDate,
    item?.policyIssueDate,
    item?.applicationDate,
    item?.dateOfApplication,
    item?.dateOfIssue,
    item?.policyCreationDate,
    item?.creationDate,
    item?.createdAt,
  ]) {
    const date = formatAllianzEpochDate(candidate);
    if (date) return date;
  }
  return "";
}


function formatAllianzPremium(premium) {
  const value = Number(premium);
  if (!Number.isFinite(value) || value <= 0) return "";
  const fixed = value.toFixed(2);
  return fixed.endsWith(".00") ? fixed.slice(0, -3) : fixed.replace(".", ",");
}

function normalizeComparableText(value) {
  return compactText(value)
    .toLocaleLowerCase("pl")
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9]+/g, "");
}

function getAllianzContext(item) {
  const context = item?.[ALLIANZ_CONTEXT_PROPERTY];
  return context && typeof context === "object" ? context : null;
}

function clientDisplayName(client) {
  const firstName = compactText(client?.firstName);
  const lastName = compactText(client?.lastName);
  if (firstName && lastName) return `${firstName} ${lastName}`;
  return compactText(client?.clientFullname) || compactText(client?.name);
}

function selectAllianzPolicyClient(items) {
  const context = (Array.isArray(items) ? items : [])
    .map(getAllianzContext)
    .find(Boolean);
  const clients = Array.isArray(context?.clients) ? context.clients : [];
  if (clients.length === 0) return null;
  const ownerName = compactText(
    items.find((item) => compactText(item?.policyOwnersName))?.policyOwnersName,
  );
  const ownerKey = normalizeComparableText(ownerName);
  const scored = clients.map((client, index) => {
    const role = compactText(client?.clientPolicyRole).toLocaleLowerCase("pl");
    const name = clientDisplayName(client);
    const nameKey = normalizeComparableText(name);
    let score = 0;
    if (/właściciel polisy|wlasciciel polisy/.test(role)) score += 60;
    else if (/użytkownik|uzytkownik/.test(role)) score += 50;
    else if (/ubezpieczony/.test(role)) score += 35;
    if (client?.clientProprietary === "OWN") score += 10;
    if (compactText(client?.pesel)) score += 20;
    if (ownerKey && nameKey && (nameKey.includes(ownerKey) || ownerKey.includes(nameKey))) score += 100;
    if (/(?:leasing|bank|towarzystwo|spółka z ograniczoną|spolka z ograniczona)/i.test(name)) score -= 40;
    return { client, index, score };
  });
  scored.sort((left, right) => right.score - left.score || left.index - right.index);
  return scored[0]?.client || null;
}

function collectDeepObjects(value, objects = [], depth = 0, seen = new Set()) {
  if (!value || typeof value !== "object" || depth > 7 || seen.has(value)) return objects;
  seen.add(value);
  if (!Array.isArray(value)) objects.push(value);
  const children = Array.isArray(value) ? value : Object.values(value);
  for (const child of children) collectDeepObjects(child, objects, depth + 1, seen);
  return objects;
}

function findAllianzDetailClient(context, selectedClient) {
  const detailObjects = collectDeepObjects(context?.detail);
  const selectedPesel = compactText(selectedClient?.pesel);
  const selectedPartyUid = compactText(selectedClient?.partyUid);
  return detailObjects.find((candidate) => (
    selectedPesel
    && compactText(candidate?.pesel) === selectedPesel
  )) || detailObjects.find((candidate) => (
    selectedPartyUid
    && compactText(candidate?.partyUid ?? candidate?.rowId) === selectedPartyUid
  )) || null;
}

function firstCompactValue(source, fieldNames) {
  for (const fieldName of fieldNames) {
    const value = compactText(source?.[fieldName]);
    if (value) return value;
  }
  return "";
}

function formatAllianzAddress(address) {
  if (!address) return "";
  if (typeof address === "string") return compactText(address).slice(0, 180);
  if (typeof address !== "object" || Array.isArray(address)) return "";
  const street = firstCompactValue(address, ["street", "streetName", "addressLine", "line1"]);
  const home = firstCompactValue(address, ["homeNumber", "houseNumber", "buildingNumber"]);
  const flat = firstCompactValue(address, ["flatNumber", "apartmentNumber"]);
  const postalCode = firstCompactValue(address, ["zipCode", "postalCode", "postCode"]);
  const city = firstCompactValue(address, ["city", "town", "place"]);
  const building = [home, flat ? `/${flat}` : ""].join("");
  return [
    [street, building].filter(Boolean).join(" "),
    [postalCode, city].filter(Boolean).join(" "),
  ].filter(Boolean).join(", ").slice(0, 180);
}

function findAllianzPostalCode(address, fallbackAddress = "") {
  const direct = firstCompactValue(address, ["zipCode", "postalCode", "postCode"]);
  if (direct) return direct;
  return compactText(fallbackAddress).match(/\b\d{2}-\d{3}\b/)?.[0] || "";
}

function getAllianzContact(detailClient, selectedClient) {
  const phone = firstCompactValue(detailClient, [
    "phoneMobile",
    "mobilePhone",
    "phoneMain",
    "phoneOther",
    "phone",
  ]) || firstCompactValue(selectedClient, [
    "phoneMobile",
    "mobilePhone",
    "phoneMain",
    "phoneOther",
    "phone",
  ]);
  const email = firstCompactValue(detailClient, ["email", "emailAddress"])
    || firstCompactValue(selectedClient, ["email", "emailAddress"]);
  return [
    phone ? `Telefon: ${phone}` : "",
    email ? `E-mail: ${email}` : "",
  ].filter(Boolean).join("\n");
}

function uniqueAllianzDocumentSources(items) {
  const unique = new Map();
  for (const item of Array.isArray(items) ? items : []) {
    const source = getAllianzPolicySource(item);
    if (!source) continue;
    const key = `${source.id}\0${source.system}\0${source.hashToCompare}`;
    if (!unique.has(key)) unique.set(key, source);
  }
  return [...unique.values()];
}

function setAllianzDocumentSources(record, items) {
  Object.defineProperty(record, "allianzDocumentSources", {
    configurable: true,
    enumerable: false,
    writable: false,
    value: uniqueAllianzDocumentSources(items),
  });
}

 
export function mapAllianzPolicies(items, {
  minEndDate = "",
  sinceDate = "",
  mappingCollector = null,
} = {}) {
  const groups = new Map();
  const groupsByPolicyEnd = new Map();
  const normalizedMinEndDate = formatAllianzEpochDate(minEndDate);
  const normalizedSinceDate = formatAllianzEpochDate(sinceDate);

  for (const item of Array.isArray(items) ? items : []) {
    const policyNumber = compactText(item?.policyName?.policyNumber);
    const status = compactText(item?.policyStatus);
    const validFrom = formatAllianzEpochDate(item?.policyStartDate);
    const validUntil = formatAllianzEpochDate(item?.policyEndDate ?? item?.expiryPolicyDate);
    if (/anulowan|cancel|storn|odst[aą]pien/i.test(status)) {
      mappingCollector?.recordFiltered("CANCELLED_POLICY");
      continue;
    }
    if (!policyNumber) {
      let identityHash = "";
      try {
        identityHash = createPortfolioIssueIdentityHash({
          insurer: "Allianz",
          sourceId: compactText(item?.id),
          policyNumber,
          validFrom,
          validUntil,
        });
      } catch {
      }
      mappingCollector?.recordRejected("MISSING_REQUIRED_FIELDS", { identityHash });
      continue;
    }
    if (normalizedMinEndDate && validUntil && validUntil < normalizedMinEndDate) {
      mappingCollector?.recordFiltered("OUTSIDE_DATE_RANGE");
      continue;
    }
    const context = getAllianzContext(item);
    const issueDate = getAllianzIssueDate({ ...(context?.detail || {}), ...item });
    if (normalizedSinceDate && issueDate && issueDate < normalizedSinceDate) {
      mappingCollector?.recordFiltered("BEFORE_INCREMENTAL_CHECKPOINT");
      continue;
    }
    const key = [
      policyNumber.replace(/[^0-9A-Za-z]/g, "").toLowerCase(),
      validFrom,
      validUntil,
    ].join("\0");
    const policyEndKey = [
      policyNumber.replace(/[^0-9A-Za-z]/g, "").toLowerCase(),
      validUntil,
    ].join("\0");
    let group = groups.get(key);
    if (!group && validUntil) {
      const samePolicyEndGroups = groupsByPolicyEnd.get(policyEndKey) || [];
      group = samePolicyEndGroups.find((candidate) => (
        candidate.validFrom === validFrom
        || !candidate.validFrom
        || !validFrom
      ));
    }
    if (!group) {
      group = {
        issueDate,
        items: [],
        policyNumber,
        status,
        validFrom,
        validUntil,
      };
      groups.set(key, group);
      if (validUntil) {
        const samePolicyEndGroups = groupsByPolicyEnd.get(policyEndKey) || [];
        samePolicyEndGroups.push(group);
        groupsByPolicyEnd.set(policyEndKey, samePolicyEndGroups);
      }
    }
    group.items.push(item);
    if (!group.issueDate && issueDate) group.issueDate = issueDate;
  }

  const records = [];
  for (const group of groups.values()) {
    const selectedClient = selectAllianzPolicyClient(group.items);
    const context = group.items.map(getAllianzContext).find(Boolean);
    const detailClient = findAllianzDetailClient(context, selectedClient);
    const fallbackName = compactText(
      group.items.find((item) => compactText(item?.policyOwnersName))?.policyOwnersName,
    ) || compactText(
      group.items.find((item) => compactText(item?.clientProprietary))?.clientProprietary,
    );
    const clientName = clientDisplayName(selectedClient) || fallbackName;
    if (!clientName) {
      let identityHash = "";
      try {
        identityHash = createPortfolioIssueIdentityHash({
          insurer: "Allianz",
          sourceId: compactText(group.items[0]?.id),
          policyNumber: group.policyNumber,
          validFrom: group.validFrom,
          validUntil: group.validUntil,
        });
      } catch {
      }
      mappingCollector?.recordRejected("MISSING_REQUIRED_FIELDS", { identityHash });
      for (let index = 1; index < group.items.length; index += 1) {
        mappingCollector?.recordDuplicate();
      }
      continue;
    }
    const pesel = firstCompactValue(selectedClient, ["pesel"])
      || firstCompactValue(detailClient, ["pesel"]);
    const nip = firstCompactValue(selectedClient, ["nip"])
      || firstCompactValue(detailClient, ["nip"]);
    const regon = firstCompactValue(selectedClient, ["regon"])
      || firstCompactValue(detailClient, ["regon"]);
    const identityNumber = pesel || regon || nip;
    const secondaryIdentityNumber = [nip, regon]
      .find((value) => value && value !== identityNumber) || "";
    const addressObject = detailClient?.addressMain
      || detailClient?.mainAddress
      || selectedClient?.addressMain
      || selectedClient?.mainAddress;
    const clientAddress = formatAllianzAddress(addressObject);
    const premiumTotal = group.items.reduce((sum, item) => {
      const value = Number(item?.amountContribution);
      return Number.isFinite(value) && value > 0 ? sum + value : sum;
    }, 0);
    const riskSummary = [...new Set(group.items
      .map((item) => compactText(item?.insuranceName))
      .filter(Boolean))]
      .join(" • ")
      .slice(0, 400);
    const record = {
      insurer: "Allianz",
      policyNumber: group.policyNumber,
      policyId: compactText(group.items[0]?.id),
      clientName: clientName.slice(0, 160),
      identityNumber: identityNumber.slice(0, 32),
      secondaryIdentityNumber: secondaryIdentityNumber.slice(0, 32),
      contact: getAllianzContact(detailClient, selectedClient).slice(0, 240),
      clientAddress,
      clientPostalCode: findAllianzPostalCode(addressObject, clientAddress),
      registration: "",
      vehicleMake: "",
      vehicleModel: "",
      vin: "",
      validFrom: group.validFrom,
      validUntil: group.validUntil,
      premium: formatAllianzPremium(premiumTotal),
      riskSummary,
      status: group.status,
      issueDate: group.issueDate,
      pdfAvailable: false,
    };
    setAllianzDocumentSources(record, group.items);
    records.push(record);
    mappingCollector?.recordMapped();
    for (let index = 1; index < group.items.length; index += 1) {
      mappingCollector?.recordDuplicate();
    }
  }
  return records;
}
