import { api, unwrap } from "./client";

function cleanParams(params = {}) {
  return Object.fromEntries(
    Object.entries(params).filter(([, value]) => value !== undefined && value !== null && value !== ""),
  );
}

export const authApi = {
  register: (payload) => api.post("/auth/register", payload).then(unwrap),
  login: (payload) => api.post("/auth/login", payload).then(unwrap),
  me: () => api.get("/auth/me").then(unwrap),
  logout: () => api.post("/auth/logout").then(unwrap),
  changePassword: (payload) => api.post("/auth/change-password", payload).then(unwrap),
};

export const contentApi = {
  list: (params) => api.get("/content", { params: cleanParams(params) }).then(unwrap),
  get: (id) => api.get(`/content/${id}`).then(unwrap),
  create: (payload) => api.post("/content", payload).then(unwrap),
  update: (id, payload) => api.patch(`/content/${id}`, payload).then(unwrap),
  remove: (id) => api.delete(`/content/${id}`).then(unwrap),
};

export const directoriesApi = {
  media: () => api.get("/media").then(unwrap),
  events: (params) => api.get("/events", { params: cleanParams(params) }).then(unwrap),
  categories: () => api.get("/categories").then(unwrap),
  tags: () => api.get("/tags").then(unwrap),
  speakers: () => api.get("/speakers").then(unwrap),
};

export const searchApi = {
  search: (q, params) => api.get("/search", { params: cleanParams({ ...params, q }) }).then(unwrap),
};

export const subscriptionsApi = {
  list: () => api.get("/subscriptions").then(unwrap),
  create: (payload) => api.post("/subscriptions", payload).then(unwrap),
};

export const notificationsApi = {
  list: () => api.get("/notifications").then(unwrap),
  markRead: (id) => api.patch(`/notifications/${id}/read`).then(unwrap),
};

export const commentsApi = {
  list: (contentId) => api.get(`/comments/${contentId}`).then(unwrap),
  create: (contentId, payload) => api.post(`/comments/${contentId}`, payload).then(unwrap),
};

export const analyticsApi = {
  summary: () => api.get("/analytics/summary").then(unwrap),
};

export const adminApi = {
  dashboard: () => api.get("/admin/dashboard").then(unwrap),
  users: (params) => api.get("/admin/users", { params: cleanParams(params) }).then(unwrap),
  roles: () => api.get("/admin/roles").then(unwrap),
  audit: (params) => api.get("/admin/audit", { params: cleanParams(params) }).then(unwrap),
};
