import { request } from "@/components/service/index";

export type ServiceStatus = "ok" | "error" | "skip";

export interface ComponentStatus {
  status: ServiceStatus;
  message?: string;
}

export interface PodStatusItem {
  name: string | null;
  phase: string | null;
}

export interface PodStatus {
  ok: boolean;
  message: string;
  running: number;
  total: number;
  pods?: PodStatusItem[];
}

export interface AdminStatusResponse {
  kfp: ComponentStatus;
  mlflow: ComponentStatus;
  minio: ComponentStatus;
  updatedAt?: string;
}

export interface AdminPodStatusResponse {
  namespace?: string;
  kfp?: PodStatus;
  mlflow?: PodStatus;
  minio?: PodStatus;
  updatedAt?: string;
  message?: string;
}

export interface RestartResponse {
  success: boolean;
  message: string;
}

/** 상태 조회 타임아웃(ms). 백엔드 없을 때 오래 기다리지 않도록 */
const STATUS_REQUEST_TIMEOUT_MS = 6_000;

export const AdminService = {
  getStatus: (): Promise<{ data: AdminStatusResponse }> =>
    request.get("/api/admin/status", {}, { timeout: STATUS_REQUEST_TIMEOUT_MS }),

  getPodStatus: (): Promise<{ data: AdminPodStatusResponse }> =>
    request.get("/api/admin/pods/status", {}, { timeout: STATUS_REQUEST_TIMEOUT_MS }),

  restart: (service: string): Promise<{ data: RestartResponse }> =>
    request.postNoParam(`/api/admin/restart/${encodeURIComponent(service)}`) as Promise<{
      data: RestartResponse;
    }>,

  /** Run별 Pod 목록 (Executions 상세 로그 버튼용). 응답: { namespace, pods: [{ name, phase }], message } */
  getPodsByRunId: (runId: string) =>
    request.get("/api/admin/pods/by-run", { runId }, { timeout: 30_000 }),

  /** 응답은 axios response. 로그 텍스트는 response.data */
  getPodLog: (params: {
    namespace: string;
    pod: string;
    container?: string;
    tailLines?: number;
  }) =>
    request.get("/api/admin/pods/logs", params as Record<string, string | number | undefined>, {
      timeout: 120_000,
      responseType: "text",
    }),

  /**
   * Run 로그. 기본: KFP처럼 한 스텝(실패 우선). allSteps=true 이면 전체 스텝.
   */
  getPodLogsByRunId: (
    runId: string,
    opts?: {
      tailLines?: number;
      allSteps?: boolean;
      podName?: string;
      stepName?: string;
      workflowName?: string;
      workflowNamespace?: string;
    },
  ) => {
    const q: Record<string, string | number | boolean> = { runId };
    if (opts?.tailLines !== undefined) q.tailLines = opts.tailLines;
    if (opts?.allSteps) q.allSteps = true;
    if (opts?.podName) q.podName = opts.podName;
    if (opts?.stepName) q.stepName = opts.stepName;
    if (opts?.workflowName) q.workflowName = opts.workflowName;
    if (opts?.workflowNamespace) q.workflowNamespace = opts.workflowNamespace;
    return request.get("/api/admin/pods/logs-by-run", q, {
      timeout: 120_000,
      responseType: "text",
    });
  },

  /** 관리자 Pod 카드: 같은 카드의 Pod 이름들 로그를 한 덩어리로 (pod 쿼리 반복) */
  getPodLogsAggregate: (namespace: string, podNames: string[], tailLines?: number) => {
    const q = new URLSearchParams();
    q.set("namespace", namespace);
    podNames.forEach((n) => {
      if (n) q.append("pod", n);
    });
    if (tailLines !== undefined) q.set("tailLines", String(tailLines));
    return request.get(`/api/admin/pods/logs-aggregate?${q.toString()}`, {}, { timeout: 120_000, responseType: "text" });
  },
};
