/**
 * Keep in sync with Dealer_Onboarding_Backend/src/common/utils/constitutionalNormalize.ts
 */

const PRIVATE_LIMITED = 'Private Limited';
const LLP = 'LLP';
const LLP_CONVERSION = 'LLP Conversion';
const PARTNERSHIP = 'Partnership';
const PARTNERSHIP_CHANGE = 'Partnership Change';
const PROPRIETORSHIP = 'Proprietorship';
const DIRECTOR_CHANGE = 'Director Change';
const OWNERSHIP_TRANSFER = 'Ownership Transfer';
const COMPANY_FORMATION = 'Company Formation';

const ALL: string[] = [
  PROPRIETORSHIP,
  PARTNERSHIP,
  LLP_CONVERSION,
  LLP,
  PRIVATE_LIMITED,
  COMPANY_FORMATION,
  OWNERSHIP_TRANSFER,
  PARTNERSHIP_CHANGE,
  DIRECTOR_CHANGE
];

export function isRegisteredConstitutionalChangeType(value: string): boolean {
  return ALL.includes(value);
}

export function normalizeToConstitutionalChangeType(raw: string | null | undefined): string | null {
  const s = String(raw || '').trim();
  if (!s) return null;
  if (isRegisteredConstitutionalChangeType(s)) return s;
  const compact = s
    .toLowerCase()
    .replace(/\./g, '')
    .replace(/\s+/g, ' ')
    .trim();
  if (
    (compact.includes('private') && (compact.includes('ltd') || compact.includes('limited'))) ||
    compact === 'pvt ltd' ||
    compact === 'pvtltd'
  ) {
    return PRIVATE_LIMITED;
  }
  if (compact.includes('llp') && compact.includes('conversion')) return LLP_CONVERSION;
  if (compact.includes('llp')) return LLP;
  if (compact.includes('partnership') && compact.includes('change')) return PARTNERSHIP_CHANGE;
  if (compact.includes('partnership')) return PARTNERSHIP;
  if (compact.includes('proprietorship') || compact === 'sole proprietorship') return PROPRIETORSHIP;
  if (compact.includes('director')) return DIRECTOR_CHANGE;
  if (compact.includes('ownership') && compact.includes('transfer')) return OWNERSHIP_TRANSFER;
  if (compact.includes('company') && compact.includes('formation')) return COMPANY_FORMATION;
  const exact = ALL.find((v) => v.toLowerCase() === s.toLowerCase());
  return exact || null;
}

export function normalizeDealerProfileConstitution(raw: string | null | undefined): string {
  return normalizeToConstitutionalChangeType(raw) || PROPRIETORSHIP;
}
