import { requestJson } from "@/shared/api/http-client"
import type { BackupScheduleSettingsDto } from "@mmapp/contracts/backups"

export type BackupItem = {
  id: string
  serverId: string
  serverName: string
  filename: string
  sizeBytes: number
  createdAt: string
  kind: "manual" | "auto"
  notes?: string
}

type CreateBackupResponse = {
  created: BackupItem[]
  failures: Array<{ serverId: string; error: string }>
}

export type CreateBackupJobResponse = {
  jobId: string
  status: "queued" | "running" | "done" | "failed"
  total: number
  completed: number
}

export type BackupJobStatusResponse = {
  id: string
  status: "queued" | "running" | "done" | "failed"
  requestedAt: string
  startedAt?: string
  finishedAt?: string
  total: number
  completed: number
  created: BackupItem[]
  failures: Array<{ serverId: string; error: string }>
}

export async function listBackups(baseUrl: string): Promise<BackupItem[]> {
  return requestJson<BackupItem[]>(baseUrl, "/api/backups")
}

export async function createBackups(
  baseUrl: string,
  payload: { serverIds: string[]; notes?: string },
): Promise<CreateBackupResponse> {
  return requestJson<CreateBackupResponse>(baseUrl, "/api/backups/create", {
    method: "POST",
    body: JSON.stringify(payload),
  })
}

export async function createBackupsAsync(
  baseUrl: string,
  payload: { serverIds: string[]; notes?: string },
): Promise<CreateBackupJobResponse> {
  return requestJson<CreateBackupJobResponse>(baseUrl, "/api/backups/create", {
    method: "POST",
    body: JSON.stringify(payload),
  })
}

export async function getBackupJob(baseUrl: string, jobId: string): Promise<BackupJobStatusResponse> {
  return requestJson<BackupJobStatusResponse>(baseUrl, `/api/backups/jobs/${jobId}`)
}

export async function deleteBackup(baseUrl: string, id: string): Promise<void> {
  await requestJson<void>(baseUrl, `/api/backups/${id}`, { method: "DELETE" })
}

export async function getBackupScheduleSettings(baseUrl: string): Promise<BackupScheduleSettingsDto> {
  return requestJson<BackupScheduleSettingsDto>(baseUrl, "/api/backups/schedule")
}

export async function putBackupScheduleSettings(
  baseUrl: string,
  payload: Partial<BackupScheduleSettingsDto>,
): Promise<BackupScheduleSettingsDto> {
  return requestJson<BackupScheduleSettingsDto>(baseUrl, "/api/backups/schedule", {
    method: "PUT",
    body: JSON.stringify(payload),
  })
}
