import { apiFetch } from "./auth";

export interface BackupItem {
  id: string;
  serverId: string;
  type: string;
  status: string;
  sizeBytes: string | null;
  sha256: string | null;
  label: string | null;
  failureReason: string | null;
  createdAt: string;
  completedAt: string | null;
}

export interface BackupListResponse {
  backups: BackupItem[];
}

export interface BackupSchedule {
  enabled: boolean;
  intervalHours: number;
  retentionCount: number;
  nextRunAt: string | null;
  lastRunAt: string | null;
}

export async function listBackups(serverId: string): Promise<BackupListResponse> {
  return apiFetch<BackupListResponse>(`/servers/${serverId}/backups`);
}

export async function createBackup(
  serverId: string,
  label?: string,
): Promise<{ backup: BackupItem; jobId?: string }> {
  return apiFetch(`/servers/${serverId}/backups`, {
    method: "POST",
    body: JSON.stringify({ label }),
  });
}

export async function deleteBackup(
  serverId: string,
  backupId: string,
): Promise<BackupItem> {
  return apiFetch(`/servers/${serverId}/backups/${backupId}`, {
    method: "DELETE",
  });
}

export async function getBackupDownloadUrl(
  serverId: string,
  backupId: string,
): Promise<{ downloadUrl: string; expiresAt: string }> {
  return apiFetch(`/servers/${serverId}/backups/${backupId}/download-url`);
}

export async function restoreBackup(
  serverId: string,
  backupId: string,
): Promise<unknown> {
  return apiFetch(`/servers/${serverId}/backups/${backupId}/restore`, {
    method: "POST",
    body: JSON.stringify({ confirm: true }),
  });
}

export async function getBackupSchedule(serverId: string): Promise<BackupSchedule> {
  return apiFetch(`/servers/${serverId}/backups/schedule`);
}

export async function updateBackupSchedule(
  serverId: string,
  input: Partial<BackupSchedule>,
): Promise<BackupSchedule> {
  return apiFetch(`/servers/${serverId}/backups/schedule`, {
    method: "PATCH",
    body: JSON.stringify(input),
  });
}
