import { apiRequest } from "./client";
import { arr, normalizeContent } from "../utils/normalizers";

function normalizeContentResponse(data: any) {
  if (Array.isArray(data)) return data.map(normalizeContent);
  return arr(data).map(normalizeContent);
}

export function getContentDetail(id) {
  return apiRequest(`/api/contents/${id}`).then(normalizeContent);
}

export function getContents(params = {}) {
  const query = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && String(value) !== "") query.set(key, String(value));
  });
  const qs = query.toString();
  return apiRequest(`/api/contents${qs ? `?${qs}` : ""}`).then(normalizeContentResponse);
}

export function markContentViewed(id) {
  return apiRequest(`/api/contents/${id}/view`, { method: "POST" });
}

export function getSuggestionBranches() {
  return apiRequest("/api/me/suggestion-branches");
}

export function createSuggestion(data) {
  return apiRequest("/api/contents", {
    method: "POST",
    data
  });
}

export function updateSuggestion(id, data) {
  return apiRequest(`/api/contents/${id}`, {
    method: "PUT",
    data
  });
}
