import { getActiveOptionsByCategory } from '@/features/foundation/master-options/service';

const JOB_TITLE_OPTION_CATEGORY = 'crm_job_title';

const BUSINESS_ROLE_FALLBACK_LABELS: Record<string, string> = {
  sales: 'Sales Engineer',
  sales_support: 'Sales Support',
  sales_manager: 'Sales Manager',
  department_manager: 'Department Manager',
  top_manager: 'General Manager'
};

function toStartCase(value: string) {
  return value
    .split('_')
    .filter(Boolean)
    .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
    .join(' ');
}

export async function getSignaturePositionLookup(organizationId: string) {
  const options = await getActiveOptionsByCategory(JOB_TITLE_OPTION_CATEGORY, { organizationId });
  return new Map(options.map((option) => [option.code, option.label]));
}

export function getBusinessRoleFallbackLabel(businessRole: string | null | undefined) {
  if (!businessRole) {
    return '-';
  }

  return BUSINESS_ROLE_FALLBACK_LABELS[businessRole] ?? toStartCase(businessRole);
}

export function resolveSignaturePositionLabel(
  businessRole: string | null | undefined,
  positionLookup: Map<string, string>
) {
  if (!businessRole) {
    return '-';
  }

  return positionLookup.get(businessRole) ?? getBusinessRoleFallbackLabel(businessRole);
}
