// =============================================================================
// Repository (Datenablage) — TypeScript types
// tdd-guard:skip — pure type declarations, no runtime logic to test.
// =============================================================================

export interface Document {
  id: string
  repository_type: 'project' | 'global_template' | 'masterdata_file'
  project_id: string | null
  storage_key: string
  original_filename: string
  title: string
  description: string | null
  document_type: string | null
  tags: string[]
  mime_type: string | null
  file_size: number | null
  checksum: string | null
  version: number
  uploaded_by: string | null
  created_at: string
  updated_at: string
  is_archived: boolean
  is_deleted: boolean
  access_scope: 'project' | 'global' | 'admin_only'
}

export interface DocumentMetadata {
  id: string
  document_id: string
  title_normalized: string | null
  keywords: string[] | null
  semantic_tags: string[] | null
  language: string | null
  country: string | null
  supplier_id: string | null
  supplier_number: string | null
  department_code: string | null
  consultant_id: string | null
  extracted_text_available: boolean
  ai_summary: string | null
  entity_json: Record<string, unknown> | null
  related_objects_json: Record<string, unknown> | null
  confidence_json: Record<string, unknown> | null
  metadata_source: 'manual' | 'imported' | 'extracted' | 'system' | null
  enrichment_status: 'pending' | 'processing' | 'completed' | 'failed'
  indexed_at: string | null
  last_enriched_at: string | null
}

export interface SupplierMasterData {
  id: string
  supplier_number: string
  supplier_name: string
  supplier_location: string | null
  plant: string | null
  country: string | null
  city: string | null
  is_active: boolean
  created_at: string
  updated_at: string
  created_by: string | null
  updated_by: string | null
}

export interface DepartmentMasterData {
  id: string
  department_code: string
  department_name: string
  organization_area: string | null
  is_active: boolean
  created_at: string
  updated_at: string
}

export interface MasterDataImportJob {
  id: string
  dataset_type: 'suppliers' | 'departments' | 'consultants'
  file_document_id: string | null
  import_status: 'pending' | 'processing' | 'completed' | 'failed'
  imported_by: string | null
  started_at: string | null
  completed_at: string | null
  summary_json: Record<string, unknown> | null
  error_json: Record<string, unknown> | null
}

export type DocumentWithMetadata = Document & { metadata?: DocumentMetadata }

export const DOCUMENT_TYPES = [
  'Bericht',
  'Präsentation',
  'Assessment',
  'Workshop',
  'Foto',
  'Vorlage',
  'Sonstiges',
] as const

export type DocumentType = (typeof DOCUMENT_TYPES)[number]

export const ALLOWED_MIME_TYPES: Record<string, string> = {
  // Documents
  pdf:  'application/pdf',
  doc:  'application/msword',
  docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  // Spreadsheets
  xls:  'application/vnd.ms-excel',
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  // Presentations
  ppt:  'application/vnd.ms-powerpoint',
  pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  // Images
  jpg:  'image/jpeg',
  jpeg: 'image/jpeg',
  png:  'image/png',
  gif:  'image/gif',
  webp: 'image/webp',
  svg:  'image/svg+xml',
  // Text / data
  txt:  'text/plain',
  csv:  'text/csv',
  json: 'application/json',
  // Archives
  zip:  'application/zip',
}

export const MAX_FILE_SIZE_BYTES = 50 * 1024 * 1024 // 50 MB

// ---------------------------------------------------------------------------
// Template categories
// ---------------------------------------------------------------------------
export const TEMPLATE_CATEGORIES = [
  'Excel Templates',
  'Assessment Templates',
  'Richtlinien',
  'Formulare',
  'Prozessstandards',
] as const

export type TemplateCategory = typeof TEMPLATE_CATEGORIES[number]

// ---------------------------------------------------------------------------
// Consultant master data (read/write from consultants table)
// ---------------------------------------------------------------------------
export interface ConsultantRecord {
  id: string
  employee_number: number | null
  first_name: string | null
  last_name: string | null
  display_name: string | null
  email: string | null
  team_code: string | null
  role: string | null
  status: string | null
  is_active: boolean
  show_in_calendar: boolean
  auth_user_id: string | null
  capacity_hours_per_day: number | null
  created_at: string | null
  updated_at: string | null
}

// ---------------------------------------------------------------------------
// Import preview row status
// ---------------------------------------------------------------------------
export type ImportRowStatus = 'new' | 'update' | 'unchanged' | 'error'

export interface SupplierImportRow {
  supplier_number: string
  supplier_name: string
  supplier_location: string | null
  plant: string | null
  country: string | null
  city: string | null
  is_active: boolean
  _status: ImportRowStatus
  _error?: string
}

export interface DepartmentImportRow {
  department_code: string
  department_name: string
  organization_area: string | null
  is_active: boolean
  _status: ImportRowStatus
  _error?: string
}

export interface ConsultantImportRow {
  first_name: string | null
  last_name: string | null
  display_name: string | null
  email: string | null
  team_code: string | null
  role: string | null
  is_active: boolean
  auth_user_id: string | null
  _status: ImportRowStatus
  _error?: string
}

// ---------------------------------------------------------------------------
// Shared utilities
// ---------------------------------------------------------------------------
export function formatFileSize(bytes: number | null | undefined): string {
  if (!bytes) return '—'
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

export function getFileIcon(mimeType: string | null | undefined): string {
  if (!mimeType) return '📄'
  if (mimeType.includes('pdf')) return '📕'
  if (mimeType.includes('excel') || mimeType.includes('spreadsheet')) return '📗'
  if (mimeType.includes('presentation') || mimeType.includes('powerpoint')) return '📙'
  if (mimeType.includes('word') || mimeType.includes('document')) return '📘'
  if (mimeType.includes('image')) return '🖼️'
  return '📄'
}

// ---------------------------------------------------------------------------
// Junction table rows (MO-25)
// ---------------------------------------------------------------------------
export interface DocumentSupplier {
  id: string
  document_id: string
  supplier_id: string
  created_at: string
}

export interface DocumentDepartment {
  id: string
  document_id: string
  department_id: string
  created_at: string
}

// Audit log
export interface MasterDataAuditLog {
  id: number
  table_name: string
  record_id: string
  action: 'create' | 'update' | 'deactivate' | 'delete' | 'import'
  changed_by: string | null
  changed_at: string
  old_data: Record<string, unknown> | null
  new_data: Record<string, unknown> | null
}

// Resolved/enriched document for display
export interface DocumentWithRelations extends Document {
  suppliers: Array<{ id: string; supplier_number: string; supplier_name: string; supplier_location: string | null }>
  departments: Array<{ id: string; department_code: string; department_name: string }>
  project_name: string | null
  uploaded_by_name: string | null
}
