/**
 * Placeholder keys used in legal markdown. Replace with actual values or safe fallbacks.
 */
export interface LegalPlaceholders {
  businessName: string;
  businessWebsite: string;
  /** e.g. "Contact us {{business.contact}}." → "Contact us at support@x.com." */
  businessContact: string;
  businessEmail: string;
  businessPhone: string;
  locationEmail: string;
  locationContact: string;
  effectiveYear: string;
}

const PLACEHOLDER_MAP: Record<string, keyof LegalPlaceholders> = {
  '{{business.name}}': 'businessName',
  '{{business.website}}': 'businessWebsite',
  '{{business.contact}}': 'businessContact',
  '{{business.email}}': 'businessEmail',
  '{{business.phone}}': 'businessPhone',
  '{{location.name}}': 'businessName',
  '{{location.email}}': 'locationEmail',
  '{{location.contact}}': 'locationContact',
  '{{right_now.year}}': 'effectiveYear',
};

export function replaceLegalPlaceholders(content: string, placeholders: LegalPlaceholders): string {
  let result = content;
  for (const [placeholder, key] of Object.entries(PLACEHOLDER_MAP)) {
    const value = placeholders[key] ?? '';
    result = result.split(placeholder).join(value);
  }
  return result;
}

export function buildLegalPlaceholders(
  companyName: string | null | undefined,
  websiteUrl: string | null | undefined,
  primaryEmail: string | null | undefined,
  primaryPhone: string | null | undefined,
  locationEmail: string | null | undefined
): LegalPlaceholders {
  const currentYear = new Date().getFullYear().toString();
  const email = primaryEmail?.trim();
  const phone = primaryPhone?.trim();
  const locEmail = locationEmail?.trim() || email;

  const businessContactPhrase =
    email ? `at ${email}` : phone ? `at ${phone}` : 'through the contact form on this website';
  const locationContactPhrase =
    locEmail ? `at ${locEmail}` : email ? `at ${email}` : 'through the contact form on this website';

  return {
    businessName: companyName?.trim() || 'The Business',
    businessWebsite: websiteUrl?.trim() || 'this website',
    businessContact: businessContactPhrase,
    businessEmail: email || 'via the contact form on this website',
    businessPhone: phone || 'the contact information provided on this website',
    locationEmail: locEmail || 'via the contact form on this website',
    locationContact: locationContactPhrase,
    effectiveYear: currentYear,
  };
}

