import type { QuotationCustomerPackageSummary } from './api/types';

const CUSTOMER_PACKAGE_ROLE_LABELS: Record<string, string> = {
  main: 'Approved PDF',
  sla: 'SLA',
  warranty: 'Warranty',
  datasheet: 'Datasheet',
  drawing: 'Drawing'
};

export type CustomerPackageUiStatus = 'not_generated' | 'generated' | 'failed';

export function getCustomerPackageRoleLabel(role: string): string {
  return (
    CUSTOMER_PACKAGE_ROLE_LABELS[role] ??
    role
      .split(/[_\s-]+/)
      .filter(Boolean)
      .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
      .join(' ')
  );
}

export function mapCustomerPackageErrorMessage(message?: string | null): string {
  const normalized = message?.trim();

  if (!normalized) {
    return 'Customer package generation failed. Please check document library configuration.';
  }

  if (
    normalized === 'Forbidden' ||
    normalized.toLowerCase().includes('permission') ||
    normalized.toLowerCase().includes('forbidden')
  ) {
    return 'You do not have permission to generate or download customer package.';
  }

  if (
    normalized === 'Assembled quotation PDF has not been generated yet.' ||
    normalized === 'Assembled quotation PDF not been generated yet.'
  ) {
    return 'Customer package has not been generated yet. Please generate it first.';
  }

  if (
    normalized === 'Approved PDF has not been generated yet' ||
    normalized === 'Approved PDF has not been generated yet.'
  ) {
    return 'Customer package requires an approved PDF first. Complete approval before generating the package.';
  }

  const missingRequiredDocument = normalized.match(/^Missing ([A-Z_ ]+) document/i);
  if (missingRequiredDocument) {
    const role = getCustomerPackageRoleLabel(missingRequiredDocument[1].toLowerCase());
    return `Cannot generate package because required ${role} document is missing.`;
  }

  return normalized;
}

export function getCustomerPackageUiStatus(input: {
  customerPackage: QuotationCustomerPackageSummary | null;
  lastErrorMessage?: string | null;
}): CustomerPackageUiStatus {
  if (input.customerPackage) {
    return 'generated';
  }

  if (input.lastErrorMessage) {
    return 'failed';
  }

  return 'not_generated';
}
