import request from '../utils/request';

export interface BackupRecord {
  id: number;
  filename: string;
  backup_type: 'MANUAL' | 'AUTO';
  content_types: string;
  file_size: number;
  created_at: string;
}

export interface BackupListResponse {
  total: number;
  items: BackupRecord[];
}

export interface BackupSettings {
  id: number;
  auto_backup_enabled: boolean;
  backup_time: string; // HH:MM
  last_backup_at?: string;
}

export interface BackupQueryParams {
  skip?: number;
  limit?: number;
  start_date?: string;
  end_date?: string;
  sort_order?: 'asc' | 'desc';
}

export interface MappingFileInfo {
  filename: string;
  app_id: string;
}

export interface RestorePreviewResponse {
  csv_headers: string[];
  db_columns: string[];
  mapping_files?: MappingFileInfo[];
}

export interface RestoreRequest {
  restore_type: 'APPLICATIONS' | 'USERS' | 'MAPPINGS';
  field_mapping: Record<string, string>;
  password: string;
  sms_code: string;
  selected_files?: string[];
}

export const getBackups = (params?: BackupQueryParams) => {
  return request({
    url: '/backups/',
    method: 'get',
    params,
  });
};

export const createBackup = () => {
  return request({
    url: '/backups/create',
    method: 'post',
  });
};

export const uploadBackup = (file: File) => {
  const formData = new FormData();
  formData.append('file', file);
  return request({
    url: '/backups/upload',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
};

export const getBackupSettings = () => {
  return request({
    url: '/backups/settings',
    method: 'get',
  });
};

export const updateBackupSettings = (data: { auto_backup_enabled: boolean; backup_time: string }) => {
  return request({
    url: '/backups/settings',
    method: 'put',
    data,
  });
};

export const getDownloadUrl = (id: number) => {
  return `/backups/download/${id}`;
};

export const previewRestore = (id: number, type: string) => {
  return request({
    url: `/backups/${id}/restore/preview`,
    method: 'get',
    params: { type }
  });
};

export const sendRestoreSms = (data: { captcha_id: string; captcha_code: string }) => {
  return request({
    url: '/backups/send-sms',
    method: 'post',
    data
  });
};

export const restoreBackup = (id: number, data: RestoreRequest) => {
  return request({
    url: `/backups/${id}/restore`,
    method: 'post',
    data
  });
};
