/**
 * Categories resource – Real HTTP implementation.
 * Endpoints: GET/POST /api/categories, PUT/DELETE /api/categories/{id}
 *
 * Backend returns ProductCategoryResponse records:
 *   { "id": "uuid", "name": "string", "description": "string|null" }
 */

import type { AxiosInstance } from 'axios';
import type {
  ProductCategoryDTO,
  CreateCategoryRequest,
  UpdateCategoryRequest,
} from '@effigenix/types';

export type {
  ProductCategoryDTO,
  CreateCategoryRequest,
  UpdateCategoryRequest,
};

// ── Resource factory ─────────────────────────────────────────────────────────

export function createCategoriesResource(client: AxiosInstance) {
  return {
    async list(): Promise<ProductCategoryDTO[]> {
      const res = await client.get<ProductCategoryDTO[]>('/api/categories');
      return res.data;
    },

    async getById(id: string): Promise<ProductCategoryDTO> {
      const res = await client.get<ProductCategoryDTO[]>('/api/categories');
      const cat = res.data.find((c) => c.id === id);
      if (!cat) throw new Error(`Kategorie nicht gefunden: ${id}`);
      return cat;
    },

    async create(request: CreateCategoryRequest): Promise<ProductCategoryDTO> {
      const res = await client.post<ProductCategoryDTO>('/api/categories', request);
      return res.data;
    },

    async update(id: string, request: UpdateCategoryRequest): Promise<ProductCategoryDTO> {
      const res = await client.put<ProductCategoryDTO>(`/api/categories/${id}`, request);
      return res.data;
    },

    async delete(id: string): Promise<void> {
      await client.delete(`/api/categories/${id}`);
    },
  };
}

export type CategoriesResource = ReturnType<typeof createCategoriesResource>;
