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

const PRIVATE_LIMITED = 'Private Limited';
const LLP = 'LLP';
const PARTNERSHIP = 'Partnership';
const PROPRIETORSHIP = 'Proprietorship';

const ALL: string[] = [
  PROPRIETORSHIP,
  PARTNERSHIP,
  LLP,
  PRIVATE_LIMITED
];

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')) return LLP;
  if (compact.includes('partnership')) return PARTNERSHIP;
  if (compact.includes('proprietorship') || compact === 'sole proprietorship') return PROPRIETORSHIP;
  const exact = ALL.find((v) => v.toLowerCase() === s.toLowerCase());
  return exact || null;
}

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