import type { Listing, User } from '@prisma/client';

export type BillingConfig = {
  accountName: string | null;
  iban: string | null;
  includeVatLine: boolean;
};

type BillingUser = Pick<User, 'billingAccountName' | 'billingIban' | 'billingIncludeVatLine'>;
type BillingListing = Pick<Listing, 'billingAccountName' | 'billingIban' | 'billingIncludeVatLine'>;

export function normalizeOptionalString(input: unknown): string | null | undefined {
  if (input === undefined) return undefined;
  if (input === null) return null;
  const value = String(input).trim();
  return value ? value : null;
}

export function normalizeIban(input: unknown): string | null | undefined {
  if (input === undefined) return undefined;
  if (input === null) return null;
  const value = String(input).replace(/\s+/g, '').toUpperCase();
  return value ? value : null;
}

export function normalizeNullableBoolean(input: unknown): boolean | null | undefined {
  if (input === undefined) return undefined;
  if (input === null) return null;
  return Boolean(input);
}

export function resolveBillingDetails(user: BillingUser, listing?: BillingListing | null): BillingConfig {
  const accountName = listing?.billingAccountName ?? user.billingAccountName ?? null;
  const iban = listing?.billingIban ?? user.billingIban ?? null;
  const includeVatLine =
    listing?.billingIncludeVatLine !== null && listing?.billingIncludeVatLine !== undefined
      ? Boolean(listing.billingIncludeVatLine)
      : Boolean(user.billingIncludeVatLine);

  return { accountName, iban, includeVatLine };
}
