import { httpClient } from './base/http-client';
import { BackupInfo, BackupConfig } from '@/services/data-management/backup';

export interface BackupListResponse {
  backups: BackupInfo[];
  scheduler: {
    isRunning: boolean;
    isEnabled: boolean;
    interval: string;
    nextBackup: string | null;
    maxBackups: number;
    backupPath: string;
  };
  config: BackupConfig;
}

export class BackupClient {
  private baseUrl = '/backups';

  /**
   * Liste toutes les sauvegardes disponibles et l'état du scheduler
   */
  async listBackups(): Promise<BackupListResponse> {
    const response = await httpClient.get<{ data: BackupListResponse }>(
      this.baseUrl
    );
    return response.data;
  }

  /**
   * Crée une nouvelle sauvegarde manuelle
   */
  async createBackup(force: boolean = false): Promise<BackupInfo | null> {
    const response = await httpClient.post<{
      data?: BackupInfo;
      skipped?: boolean;
      message?: string;
    }>(this.baseUrl, {
      action: 'create',
      force,
    });

    if (response.skipped) {
      return null; // Backup was skipped
    }

    return response.data!;
  }

  /**
   * Vérifie l'intégrité de la base de données
   */
  async verifyDatabase(): Promise<void> {
    await httpClient.post(this.baseUrl, {
      action: 'verify',
    });
  }

  /**
   * Met à jour la configuration des sauvegardes
   */
  async updateConfig(config: Partial<BackupConfig>): Promise<BackupConfig> {
    const response = await httpClient.post<{ data: BackupConfig }>(
      this.baseUrl,
      {
        action: 'config',
        config,
      }
    );
    return response.data;
  }

  /**
   * Démarre ou arrête le planificateur automatique
   */
  async toggleScheduler(enabled: boolean): Promise<{
    isRunning: boolean;
    isEnabled: boolean;
    interval: string;
    nextBackup: string | null;
    maxBackups: number;
    backupPath: string;
  }> {
    const response = await httpClient.post<{
      data: {
        isRunning: boolean;
        isEnabled: boolean;
        interval: string;
        nextBackup: string | null;
        maxBackups: number;
        backupPath: string;
      };
    }>(this.baseUrl, {
      action: 'scheduler',
      enabled,
    });
    return response.data;
  }

  /**
   * Supprime une sauvegarde
   */
  async deleteBackup(filename: string): Promise<void> {
    await httpClient.delete(`${this.baseUrl}/${filename}`);
  }

  /**
   * Restaure une sauvegarde (développement uniquement)
   */
  async restoreBackup(filename: string): Promise<void> {
    await httpClient.post(`${this.baseUrl}/${filename}`, {
      action: 'restore',
    });
  }

  /**
   * Récupère les logs de backup
   */
  async getBackupLogs(maxLines: number = 100): Promise<string[]> {
    const response = await httpClient.get<{ data: { logs: string[] } }>(
      `${this.baseUrl}?action=logs&maxLines=${maxLines}`
    );
    return response.data.logs;
  }

  /**
   * Récupère les statistiques de sauvegarde par jour
   */
  async getBackupStats(days: number = 30): Promise<
    Array<{
      date: string;
      manual: number;
      automatic: number;
      total: number;
    }>
  > {
    const response = await httpClient.get<{
      data: Array<{
        date: string;
        manual: number;
        automatic: number;
        total: number;
      }>;
    }>(`${this.baseUrl}?action=stats&days=${days}`);
    return response.data;
  }
}

export const backupClient = new BackupClient();
