import { apiRequest, getApiBaseUrl } from './api';

export type ExportEntity = 'leads' | 'contacts' | 'accounts' | 'deals' | 'projects' | 'timesheets' | 'customers';
export type ImportEntity = 'leads' | 'contacts' | 'accounts' | 'deals' | 'customers';

export interface ImportPreviewRow extends Record<string, unknown> {
  _rowNumber?: number;
  _fileLine?: number;
  _isValid?: boolean;
  _errors?: string[];
}

export interface ImportPreviewResult {
  totalRows: number;
  headers: string[];
  validCount: number;
  validRows: number;
  errorCount: number;
  sampleRows: ImportPreviewRow[];
  previewRows?: ImportPreviewRow[];
  errors: Array<{ row: number; field?: string; message: string }>;
}

export interface ImportCommitResult {
  importedCount: number;
  totalRows: number;
  errorCount: number;
  errors: Array<{ row: number; message: string }>;
}

export interface BackupLogRecord {
  id: string;
  fileName: string;
  mimeType?: string;
  sizeBytes: number;
  createdAt: string;
  status: string;
  uploadedBy?: {
    id: string;
    name: string;
    email: string;
  } | null;
}

export interface BackupCreateResult {
  id: string;
  fileName: string;
  sizeBytes: number;
  format?: 'sql' | 'json';
  counts: Record<string, number>;
  totalRecords?: number;
  createdAt: string;
  uploadedBy?: {
    id: string;
    name: string;
    email: string;
  } | null;
}

export const dataOpsApi = {
  // Downloads the exported Excel spreadsheet (.xlsx) directly via authenticated blob response
  exportExcel: async (entity: ExportEntity, params?: Record<string, unknown>): Promise<void> => {
    const token = typeof window !== 'undefined' ? localStorage.getItem('tcx_access_token') : null;
    const baseUrl = getApiBaseUrl();
    const query = new URLSearchParams();
    if (params) {
      for (const [k, v] of Object.entries(params)) {
        if (v !== undefined && v !== null && v !== '') {
          query.set(k, String(v));
        }
      }
    }
    const qs = query.toString() ? `?${query.toString()}` : '';
    const res = await fetch(`${baseUrl}/data/export/${encodeURIComponent(entity)}${qs}`, {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
      credentials: 'include',
    });
    if (!res.ok) {
      const err = await res.json().catch(() => ({ message: 'Export failed' }));
      throw new Error(err.message || `Export failed with status ${res.status}`);
    }
    const blob = await res.blob();
    const disposition = res.headers.get('content-disposition') || '';
    const match = disposition.match(/filename="?([^";]+)"?/);
    const filename = match ? match[1] : `${entity}-${new Date().toISOString().slice(0, 10)}.xlsx`;

    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url);
  },

  // Backward compatible alias
  exportCsv: async (entity: ExportEntity, params?: Record<string, unknown>): Promise<void> => {
    return dataOpsApi.exportExcel(entity, params);
  },

  // Downloads the exported PDF report directly via authenticated blob response
  exportPdf: async (entity: ExportEntity, params?: Record<string, unknown>): Promise<void> => {
    const token = typeof window !== 'undefined' ? localStorage.getItem('tcx_access_token') : null;
    const baseUrl = getApiBaseUrl();
    const query = new URLSearchParams();
    if (params) {
      for (const [k, v] of Object.entries(params)) {
        if (v !== undefined && v !== null && v !== '') {
          query.set(k, String(v));
        }
      }
    }
    const qs = query.toString() ? `?${query.toString()}` : '';
    const res = await fetch(`${baseUrl}/data/export/${encodeURIComponent(entity)}/pdf${qs}`, {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
      credentials: 'include',
    });
    if (!res.ok) {
      const err = await res.json().catch(() => ({ message: 'PDF export failed' }));
      throw new Error(err.message || `PDF export failed with status ${res.status}`);
    }
    const blob = await res.blob();
    const disposition = res.headers.get('content-disposition') || '';
    const match = disposition.match(/filename="?([^";]+)"?/);
    const filename = match ? match[1] : `${entity}-report-${new Date().toISOString().slice(0, 10)}.pdf`;

    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url);
  },

  // Downloads a blank Excel template (.xlsx) with expected headers and sample rows for import
  downloadTemplate: async (entity: string): Promise<void> => {
    const token = typeof window !== 'undefined' ? localStorage.getItem('tcx_access_token') : null;
    const baseUrl = getApiBaseUrl();
    const res = await fetch(`${baseUrl}/data/template/${encodeURIComponent(entity)}`, {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
      credentials: 'include',
    });
    if (!res.ok) {
      const err = await res.json().catch(() => ({ message: 'Download template failed' }));
      throw new Error(err.message || `Download template failed with status ${res.status}`);
    }
    const blob = await res.blob();
    const disposition = res.headers.get('content-disposition') || '';
    const match = disposition.match(/filename="?([^";]+)"?/);
    const filename = match ? match[1] : `${entity}_template.xlsx`;

    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url);
  },

  previewImport: (entity: ImportEntity, csvContent: string) =>
    apiRequest<ImportPreviewResult>('/data/import/preview', {
      method: 'POST',
      body: JSON.stringify({ entity, csvContent }),
    }),

  commitImport: (entity: ImportEntity, csvContent: string) =>
    apiRequest<ImportCommitResult>('/data/import/commit', {
      method: 'POST',
      body: JSON.stringify({ entity, csvContent }),
    }),

  createBackup: (format: 'sql' | 'json' = 'sql') =>
    apiRequest<BackupCreateResult>('/data/backup', {
      method: 'POST',
      body: JSON.stringify({ format }),
    }),

  getBackupLogs: () => apiRequest<BackupLogRecord[]>('/data/backup/logs'),

  downloadBackup: async (fileId: string, defaultName = 'database-backup.sql'): Promise<void> => {
    const token = typeof window !== 'undefined' ? localStorage.getItem('tcx_access_token') : null;
    const baseUrl = getApiBaseUrl();
    const res = await fetch(`${baseUrl}/data/backup/download/${encodeURIComponent(fileId)}`, {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
      credentials: 'include',
    });
    if (!res.ok) {
      const err = await res.json().catch(() => ({ message: 'Failed to download backup' }));
      throw new Error(err.message || `Failed to download backup: ${res.statusText}`);
    }
    const blob = await res.blob();
    const disposition = res.headers.get('content-disposition') || '';
    const match = disposition.match(/filename="?([^";]+)"?/);
    const filename = match ? match[1] : defaultName;

    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url);
  },
};
