import { CONSTITUTIONAL_CHANGE_TYPES } from '../config/constants.js';

const ALL_CHANGE_TYPES = Object.values(CONSTITUTIONAL_CHANGE_TYPES) as string[];

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

/**
 * Map UI / legacy profile labels to a value that exists on `constitutional_changes.changeType` ENUM.
 */
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 CONSTITUTIONAL_CHANGE_TYPES.PRIVATE_LIMITED;
  }
  if (compact.includes('llp')) {
    return CONSTITUTIONAL_CHANGE_TYPES.LLP;
  }
  if (compact.includes('partnership')) {
    return CONSTITUTIONAL_CHANGE_TYPES.PARTNERSHIP;
  }
  if (compact.includes('proprietorship') || compact === 'sole proprietorship') {
    return CONSTITUTIONAL_CHANGE_TYPES.PROPRIETORSHIP;
  }
  const exact = ALL_CHANGE_TYPES.find((v) => v.toLowerCase() === s.toLowerCase());
  return exact || null;
}

/**
 * Maps `constitutional_changes.changeType` → `dealers.constitutionType` when the workflow completes.
 * Returns `null` when the change type does not represent a single target legal structure (skip master update).
 */
export function mapConstitutionalChangeTypeToDealerProfile(changeType: string): string | null {
  const t = String(changeType || '').trim();
  if (!t) return null;

  const structureTargets = [
    CONSTITUTIONAL_CHANGE_TYPES.PROPRIETORSHIP,
    CONSTITUTIONAL_CHANGE_TYPES.PARTNERSHIP,
    CONSTITUTIONAL_CHANGE_TYPES.LLP,
    CONSTITUTIONAL_CHANGE_TYPES.PRIVATE_LIMITED
  ];
  if (structureTargets.includes(t as (typeof structureTargets)[number])) return t;

  return null;
}
