import adminClient from "./client"
import type { ApiResponse } from "../../types"

export type ServiceStatus = "ok" | "error" | "disabled" | string

export interface AdminLicenseInfo {
  required: boolean
  configured: boolean
  status: "active" | "missing" | "unavailable" | "grace" | string
  grace_until?: string
  license_no?: string
  type?: string
  version?: string
  purchase?: string
  expire?: string
  service_purchase?: string
  service_expire?: string
  verified_at?: string
  instance_name?: string
  system_name?: string
  system_arch?: string
  backend_url?: string
  last_online?: string
  running_version?: string
}

export interface AdminUpdateInfo {
  status: ServiceStatus
  version?: string
  update_url?: string
  db_update_required?: boolean
  update_time?: string
  changelog?: string
  force_update_required?: boolean
}

export interface AdminSystemInfo {
  app: {
    name: string
    version: string
    backend_type?: "go" | "python" | string
    started_at: string
    current_time: string
    uptime_seconds: number
  }
  runtime?: {
    go_version: string
    os: string
    arch: string
    cpus: number
    goroutines: number
    memory: {
      alloc_mb: number
      heap_alloc_mb: number
      sys_mb: number
      num_gc: number
    }
  }
  database: {
    enabled: boolean
    status: ServiceStatus
    latency_ms?: number
    open_connections?: number
    in_use?: number
    idle?: number
    max_open_connections?: number
    wait_count?: number
    error?: string
  }
  redis: {
    enabled: boolean
    status: ServiceStatus
    latency_ms?: number
    error?: string
  }
  settings: {
    mode: string
  }
  plugins: {
    enabled: boolean
  }
  license?: AdminLicenseInfo
  update?: AdminUpdateInfo
}

export async function getAdminSystemInfo() {
  const { data } = await adminClient.get<ApiResponse<AdminSystemInfo>>("/v1/admin/system-info")
  return data
}

export async function getAdminLicenseStatus() {
  const { data } = await adminClient.get<ApiResponse<AdminLicenseInfo>>("/v1/admin/license-status")
  return data
}

export async function activateAdminLicenseCode(licenseCode: string) {
  const { data } = await adminClient.post<ApiResponse<{ configured: boolean }>>(
    "/v1/admin/license/activate",
    { licenseCode: licenseCode.trim() },
  )
  return data
}
