import { getKbxField, type KbxKnownFieldKey } from './generated/fieldCatalog'

export type KbxImportStatus =
  | 'created'
  | 'uploaded'
  | 'mapping-required'
  | 'validating'
  | 'validated'
  | 'committing'
  | 'completed'
  | 'partially-completed'
  | 'failed'
  | 'cancelled'

export type KbxImportMappingSource = 'exact' | 'alias' | 'saved' | 'ai' | 'manual'

export interface KbxImportFieldDefinition {
  key: string
  label: string
  aliases?: string[]
  dataType:
    | 'text'
    | 'code'
    | 'integer'
    | 'decimal'
    | 'quantity'
    | 'money'
    | 'date'
    | 'datetime'
    | 'boolean'
    | 'lookup'
  required?: boolean
  maxLength?: number
  precision?: number
  scale?: number
  lookupEntity?: string
  importable?: boolean
  exportable?: boolean
  helpText?: string
  sensitive?: boolean
  masking?: 'name' | 'phone' | 'address' | 'partial'
}

export interface KbxImportDefinition {
  id: string
  screenId: string
  entity: string
  title: string
  fields: KbxImportFieldDefinition[]
  allowCreate: boolean
  allowUpdate: boolean
  maxFileSizeBytes?: number
  maxRows?: number
}

export interface KbxImportMapping {
  sourceColumn: string
  targetField: string | null
  source: KbxImportMappingSource
  confidence?: number
  reason?: string
}

export interface KbxImportValidationError {
  rowNumber: number
  field?: string
  sourceColumn?: string
  code: string
  message: string
  severity: 'error' | 'warning'
}

export interface KbxImportFailure {
  code: string
  title: string
  detail?: string
  recoverable?: boolean
}

export interface KbxImportSession {
  id: string
  importType: string
  screenId: string
  fileName: string
  status: KbxImportStatus
  totalRows: number
  validRows: number
  invalidRows: number
  warningRows: number
  createdRows: number
  updatedRows: number
  progressPercent: number
  mapping: KbxImportMapping[]
  sourceColumns: string[]
  errors?: KbxImportValidationError[]
  failure?: KbxImportFailure
  createdAt: string
  completedAt?: string
}

export interface KbxImportProgressEvent {
  sessionId: string
  status: KbxImportStatus
  progressPercent: number
  totalRows: number
  processedRows: number
  validRows: number
  invalidRows: number
  warningRows: number
  message?: string
}

export interface KbxSavedImportMapping {
  id: string
  importType: string
  name: string
  mappings: KbxImportMapping[]
  updatedAt: string
}


/**
 * Materialize Excel metadata from the canonical KBX Field Dictionary.
 * Screen/import definitions may select fields, but should not duplicate label/type/length/alias metadata.
 */
export function kbxImportField(
  key: KbxKnownFieldKey,
  overrides: Partial<KbxImportFieldDefinition> = {},
): KbxImportFieldDefinition {
  const field = getKbxField(key) as any
  if (!field.importable && overrides.importable !== true) {
    throw new Error(`${key} is not importable in the KBX field dictionary.`)
  }
  return {
    key,
    label: field.label,
    aliases: field.aliases ?? [],
    dataType: field.dataType,
    required: Boolean(field.required),
    maxLength: field.maxLength,
    precision: field.precision,
    scale: field.scale,
    lookupEntity: field.lookupEntity,
    importable: Boolean(field.importable),
    exportable: Boolean(field.exportable),
    helpText: field.helpText,
    sensitive: Boolean(field.sensitive),
    masking: field.masking,
    ...overrides,
  }
}
