/**
 * 业务运行上下文 / 沙箱配置 API。
 */

import { apiClient } from "./client";

export type RuntimeMode = "live" | "sandbox";
export type AIMode = "live";
export type RuntimeStepStatus = "success" | "skipped" | "warning" | "failed";

export interface RuntimeContext {
  site_id: number;
  mode: RuntimeMode;
  business_day_start_hour: number;
  business_date: string;
  business_now: string;
  sandbox_date: string | null;
  sandbox_instance_id: string | null;
  ai_mode: AIMode;
  status: string;
  is_sandbox: boolean;
}

export interface RuntimeSiteItem {
  site_id: number;
  site_name: string | null;
  site_code: string | null;
  is_active: boolean;
  mode: RuntimeMode | null;
  sandbox_date: string | null;
  sandbox_instance_id: string | null;
  ai_mode: AIMode | null;
  status: string | null;
  updated_at: string | null;
}

export interface RuntimeSwitchRequest {
  site_id: number;
  mode: RuntimeMode;
  sandbox_date?: string | null;
  reset_sandbox?: boolean;
  reason?: string | null;
}

export interface RuntimeTransitionStep {
  key: string;
  title: string;
  status: RuntimeStepStatus;
  detail: string;
  count: number;
}

export interface RuntimeSwitchResponse {
  context: RuntimeContext;
  steps: RuntimeTransitionStep[];
}

export async function fetchRuntimeSites(): Promise<RuntimeSiteItem[]> {
  const { data } = await apiClient.get<RuntimeSiteItem[]>("/admin/runtime-context/sites");
  return data;
}

export async function fetchRuntimeContext(siteId: number): Promise<RuntimeContext> {
  const { data } = await apiClient.get<RuntimeContext>("/admin/runtime-context", {
    params: { site_id: siteId },
  });
  return data;
}

export async function switchRuntimeContext(
  payload: RuntimeSwitchRequest,
): Promise<RuntimeSwitchResponse> {
  const { data } = await apiClient.patch<RuntimeSwitchResponse>(
    "/admin/runtime-context",
    payload,
  );
  return data;
}
