import api from '../utils/request'

export interface MappingRow {
  row_index: number
  mobile: string
  mapped_key: string
  status: 'NEW' | 'UPDATE' | 'ERROR'
  message?: string
}

export interface PreviewResponse {
  total_rows: number
  valid_count: number
  error_count: number
  new_count: number
  update_count: number
  preview_rows: MappingRow[]
}

export interface ImportSummary {
  total_processed: number
  inserted: number
  updated: number
  failed: number
}

export interface ImportLogItem {
  import_time: string
  mobile: string
  mapped_key: string
  status: 'Success' | 'Failed' | 'Skipped'
  message: string
  is_unified_account_created: boolean
  generated_password?: string
  mapped_email?: string
}

export interface ImportLogResponse {
  summary: ImportSummary
  logs: ImportLogItem[]
}

export const previewMapping = (appId: number, file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  return api.post<PreviewResponse>(`/apps/${appId}/mapping/preview`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

export const sendImportVerificationCode = () => {
    return api.post('/apps/send-import-verification-code')
}

export const importMapping = (appId: number, file: File, strategy: 'SKIP' | 'OVERWRITE', verificationCode: string) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('strategy', strategy)
  formData.append('verification_code', verificationCode)
  return api.post<ImportLogResponse>(`/apps/${appId}/mapping/import`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}
