/**
 * 运维控制面板 API
 *
 * 对接后端 /api/ops/* 端点，提供服务状态、Git 操作、系统信息等。
 */

import { apiClient } from "./client";

// ---- 类型定义 ----

export interface SystemInfo {
  cpu_percent: number;
  memory_total_gb: number;
  memory_used_gb: number;
  memory_percent: number;
  disk_total_gb: number;
  disk_used_gb: number;
  disk_percent: number;
  boot_time: string;
}

export interface ServiceStatus {
  env: string;
  label: string;
  running: boolean;
  pid: number | null;
  port: number;
  uptime_seconds: number | null;
  memory_mb: number | null;
  cpu_percent: number | null;
}

export interface GitInfo {
  env: string;
  branch: string;
  last_commit_hash: string;
  last_commit_message: string;
  last_commit_time: string;
  has_local_changes: boolean;
}

export interface ActionResult {
  env: string;
  action: string;
  success: boolean;
  message: string;
}

export interface GitPullResult {
  env: string;
  success: boolean;
  output: string;
}

// ---- API 调用 ----

export async function fetchSystemInfo(): Promise<SystemInfo> {
  const { data } = await apiClient.get<SystemInfo>("/ops/system");
  return data;
}

export async function fetchServicesStatus(): Promise<ServiceStatus[]> {
  const { data } = await apiClient.get<ServiceStatus[]>("/ops/services");
  return data;
}

export async function fetchGitInfo(): Promise<GitInfo[]> {
  const { data } = await apiClient.get<GitInfo[]>("/ops/git");
  return data;
}

export async function startService(env: string): Promise<ActionResult> {
  const { data } = await apiClient.post<ActionResult>(`/ops/services/${env}/start`);
  return data;
}

export async function stopService(env: string): Promise<ActionResult> {
  const { data } = await apiClient.post<ActionResult>(`/ops/services/${env}/stop`);
  return data;
}

export async function restartService(env: string): Promise<ActionResult> {
  const { data } = await apiClient.post<ActionResult>(`/ops/services/${env}/restart`);
  return data;
}

export async function gitPull(env: string): Promise<GitPullResult> {
  const { data } = await apiClient.post<GitPullResult>(`/ops/git/${env}/pull`);
  return data;
}

export async function syncDeps(env: string): Promise<ActionResult> {
  const { data } = await apiClient.post<ActionResult>(`/ops/git/${env}/sync-deps`);
  return data;
}

export async function fetchEnvFile(env: string): Promise<{ env: string; content: string }> {
  const { data } = await apiClient.get<{ env: string; content: string }>(`/ops/env-file/${env}`);
  return data;
}
