import api from './api';

export interface CategoryItem {
  id: number;
  name: string;
  description?: string;
}

export async function getCategories(): Promise<CategoryItem[]> {
  const res = await api.get<CategoryItem[] | { items?: CategoryItem[]; data?: CategoryItem[] }>(
    '/categories'
  );
  const d: any = res.data;
  if (Array.isArray(d)) return d as CategoryItem[];
  if (d && Array.isArray(d.items)) return d.items as CategoryItem[];
  if (d && Array.isArray(d.data)) return d.data as CategoryItem[];
  return [];
}

export async function createCategory(payload: { name: string; description?: string }): Promise<CategoryItem> {
  const res = await api.post<CategoryItem>('/admin/categories', payload);
  return res.data;
}

export async function updateCategory(id: number | string, payload: { name?: string; description?: string }): Promise<CategoryItem> {
  const res = await api.put<CategoryItem>(`/admin/categories/${id}`, payload);
  return res.data;
}

export async function deleteCategory(id: number | string): Promise<void> {
  await api.delete(`/admin/categories/${id}`);
}
