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

const BASE_URL = API_BASE_URL;

// --- Types ---

export type PageInfo = {
  id: string;
  name: string;
  description: string;
  content_type: string;  // "html" | "url" | "folder" | "bundle"
  parent_id: string | null;
  filename: string | null;
  size_bytes: number;
  entry_file: string | null;
  url: string | null;
  frameable: boolean | null;
};

// --- Folder API ---

export async function createFolder(name: string, description: string = "", parentId?: string): Promise<PageInfo> {
  const res = await fetch(`${BASE_URL}/api/pages/folders`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name, description, parent_id: parentId || null }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.detail || "Failed to create folder");
  }
  return res.json();
}

export async function fetchBreadcrumb(pageId: string): Promise<PageInfo[]> {
  const res = await fetch(`${BASE_URL}/api/pages/breadcrumb/${pageId}`);
  if (!res.ok) throw new Error("Failed to fetch breadcrumb");
  return res.json();
}

// --- Bookmark API ---

export async function createBookmark(name: string, url: string, description: string = "", parentId?: string): Promise<PageInfo> {
  const res = await fetch(`${BASE_URL}/api/pages/bookmark`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name, url, description, parent_id: parentId || null }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.detail || "Failed to create bookmark");
  }
  return res.json();
}

// --- Frameable check ---

export async function checkFrameable(pageId: string): Promise<boolean> {
  const res = await fetch(`${BASE_URL}/api/pages/check-frameable/${pageId}`, {
    method: "POST",
  });
  if (!res.ok) return true;
  const data = await res.json();
  return data.frameable !== false;
}

// --- Page API ---

export async function fetchPages(parentId?: string | null): Promise<PageInfo[]> {
  const params = parentId !== undefined ? `?parent_id=${parentId ?? "null"}` : "";
  const res = await fetch(`${BASE_URL}/api/pages/${params}`);
  if (!res.ok) throw new Error("Failed to fetch pages");
  return res.json();
}

export async function fetchPage(id: string): Promise<PageInfo> {
  const res = await fetch(`${BASE_URL}/api/pages/${id}`);
  if (!res.ok) throw new Error("Failed to fetch page");
  return res.json();
}

export function getPageContentUrl(page: PageInfo | string): string {
  if (typeof page === "string") {
    return `${BASE_URL}/api/pages/${page}/content`;
  }
  if (page.content_type === "bundle" && page.entry_file) {
    return `${BASE_URL}/api/pages/${page.id}/content/${page.entry_file}`;
  }
  return `${BASE_URL}/api/pages/${page.id}/content`;
}

export async function uploadPage(file: File, name: string, description: string = "", parentId?: string): Promise<PageInfo> {
  const formData = new FormData();
  formData.append("file", file);
  formData.append("name", name);
  formData.append("description", description);
  if (parentId) formData.append("parent_id", parentId);
  const res = await fetch(`${BASE_URL}/api/pages/upload`, {
    method: "POST",
    body: formData,
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.detail || "Failed to upload page");
  }
  return res.json();
}

export async function uploadBundle(files: File[], name: string, description: string = "", parentId?: string): Promise<PageInfo> {
  const formData = new FormData();
  for (const file of files) {
    formData.append("files", file);
  }
  formData.append("name", name);
  formData.append("description", description);
  if (parentId) formData.append("parent_id", parentId);
  const res = await fetch(`${BASE_URL}/api/pages/upload-bundle`, {
    method: "POST",
    body: formData,
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.detail || "Failed to upload bundle");
  }
  return res.json();
}

export async function importPageFromPath(path: string, name: string, description: string = "", parentId?: string): Promise<PageInfo> {
  const res = await fetch(`${BASE_URL}/api/pages/import`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ path, name, description, parent_id: parentId || null }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.detail || "Failed to import page");
  }
  return res.json();
}

export async function updatePage(id: string, updates: { name?: string; description?: string; parent_id?: string | null }): Promise<PageInfo> {
  const res = await fetch(`${BASE_URL}/api/pages/${id}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(updates),
  });
  if (!res.ok) throw new Error("Failed to update page");
  return res.json();
}

export async function deletePage(id: string): Promise<void> {
  const res = await fetch(`${BASE_URL}/api/pages/${id}`, {
    method: "DELETE",
  });
  if (!res.ok) throw new Error("Failed to delete page");
}
