interface ContractInfoData {
  type: string;
  address?: { street: string; houseNumber: string; postalCode: string; city: string } | null;
  mobileDetails?: {
    phoneNumber: string | null;
    mobileNetwork?: string | null;
    simCards: { phoneNumber: string | null; isMain: boolean; cardUser?: string | null }[];
  } | null;
  carInsuranceDetails?: { licensePlate: string | null } | null;
}

export interface ContractTypeInfo {
  label: string;
  value: string;
  // Nur bei Mobilfunk zusätzlich befüllt:
  cardUser?: string;  // wem die Karte gehört (SimCard.cardUser)
  network?: string;   // Mobilfunknetz, menschenlesbar (Telekom/Vodafone/…)
}

// Physisches Mobilfunknetz → Anzeigename.
const MOBILE_NETWORK_LABELS: Record<string, string> = {
  TELEKOM: 'Telekom',
  VODAFONE: 'Vodafone',
  TELEFONICA: 'Telefónica (o2)',
};

export function mobileNetworkLabel(net?: string | null): string | undefined {
  if (!net) return undefined;
  return MOBILE_NETWORK_LABELS[net] ?? net;
}

export function getContractTypeInfo(contract: ContractInfoData): ContractTypeInfo | null {
  const { type } = contract;

  if (type === 'ELECTRICITY' || type === 'GAS') {
    const a = contract.address;
    if (!a) return null;
    return {
      label: 'Lieferadresse',
      value: `${a.street} ${a.houseNumber}, ${a.postalCode} ${a.city}`,
    };
  }

  if (type === 'DSL' || type === 'FIBER' || type === 'CABLE') {
    const a = contract.address;
    if (!a) return null;
    return {
      label: 'Anschlussadresse',
      value: `${a.street} ${a.houseNumber}, ${a.postalCode} ${a.city}`,
    };
  }

  if (type === 'MOBILE') {
    const md = contract.mobileDetails;
    if (!md) return null;
    const mainSim = md.simCards?.find((s) => s.isMain && s.phoneNumber);
    const anySim = md.simCards?.find((s) => s.phoneNumber);
    const sim = mainSim || anySim;
    const phone = sim?.phoneNumber || md.phoneNumber;
    if (!phone) return null;
    return {
      label: 'Rufnummer',
      value: phone,
      // Karteninhaber der angezeigten SIM (kann vom Vertragsinhaber abweichen).
      cardUser: sim?.cardUser?.trim() || undefined,
      network: mobileNetworkLabel(md.mobileNetwork),
    };
  }

  if (type === 'CAR_INSURANCE') {
    const plate = contract.carInsuranceDetails?.licensePlate;
    if (!plate) return null;
    return { label: 'Kennzeichen', value: plate };
  }

  return null;
}
