import { API_BASE_URL } from "@/lib/config";

const BASE_URL = API_BASE_URL;

// --- Types ---

export type LLMSettings = {
  model: string;
  api_base: string | null;
  api_key: string | null;
  temperature: number;
  max_tokens: number;
  system_prompt: string;
};

export type HealthResult = {
  server: string;
  llm_connected: boolean;
  model: string;
  error: string | null;
};

export type ProfileSettings = {
  name: string;
  avatar: string;
  platform_name: string;
  platform_subtitle: string;
  bot_name: string;
  bot_avatar: string;
};

export type ApiThemeSettings = {
  accent_color: string;
  mode: string;
  tone: string;
  show_blobs: boolean;
  chat_bg_image: string;
  chat_bg_opacity: number;
  chat_bg_scale: number;
  chat_bg_position_x: number;
  chat_bg_position_y: number;
};

export type VersionInfo = {
  current: string;
  latest: string | null;
  update_available: boolean;
};

// --- API Functions ---

export async function checkHealth(): Promise<HealthResult> {
  try {
    const res = await fetch(`${BASE_URL}/api/settings/health`, { signal: AbortSignal.timeout(15000) });
    if (!res.ok) throw new Error("Server error");
    return res.json();
  } catch {
    return { server: "error", llm_connected: false, model: "", error: "백엔드 서버에 연결할 수 없습니다" };
  }
}

export async function fetchVersion(): Promise<VersionInfo> {
  try {
    const res = await fetch(`${BASE_URL}/api/settings/version`, { signal: AbortSignal.timeout(10000) });
    if (!res.ok) throw new Error("Failed to fetch version");
    return res.json();
  } catch {
    return { current: "unknown", latest: null, update_available: false };
  }
}

export async function fetchLLMSettings(): Promise<LLMSettings> {
  const res = await fetch(`${BASE_URL}/api/settings/llm`);
  if (!res.ok) throw new Error("Failed to fetch LLM settings");
  return res.json();
}

export async function updateLLMSettings(updates: Partial<LLMSettings>): Promise<LLMSettings> {
  const res = await fetch(`${BASE_URL}/api/settings/llm`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(updates),
  });
  if (!res.ok) throw new Error("Failed to update LLM settings");
  return res.json();
}

export async function fetchProfile(): Promise<ProfileSettings> {
  const res = await fetch(`${BASE_URL}/api/settings/profile`);
  if (!res.ok) throw new Error("Failed to fetch profile");
  return res.json();
}

export async function updateProfile(updates: Partial<ProfileSettings>): Promise<ProfileSettings> {
  const res = await fetch(`${BASE_URL}/api/settings/profile`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(updates),
  });
  if (!res.ok) throw new Error("Failed to update profile");
  return res.json();
}

export async function fetchTheme(): Promise<ApiThemeSettings> {
  const res = await fetch(`${BASE_URL}/api/settings/theme`);
  if (!res.ok) throw new Error("Failed to fetch theme");
  return res.json();
}

export async function updateTheme(updates: Partial<ApiThemeSettings>): Promise<ApiThemeSettings> {
  const res = await fetch(`${BASE_URL}/api/settings/theme`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(updates),
  });
  if (!res.ok) throw new Error("Failed to update theme");
  return res.json();
}
