import type { APIRoute } from 'astro';
import { getCategoryTree, createCategory, updateCategory, deleteCategory } from '../../../lib/categories/category-manager.js';

export const GET: APIRoute = async ({ url }) => {
  try {
    const dimension = url.searchParams.get('dimension') || undefined;
    const tree = await getCategoryTree(dimension);
    return new Response(JSON.stringify({ categories: tree }), {
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (e: any) {
    return new Response(JSON.stringify({ error: e.message }), { status: 500 });
  }
};

export const POST: APIRoute = async ({ request }) => {
  try {
    const data = await request.json();
    const category = await createCategory(data);
    return new Response(JSON.stringify(category), {
      status: 201,
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (e: any) {
    return new Response(JSON.stringify({ error: e.message }), { status: 400 });
  }
};

export const PUT: APIRoute = async ({ request }) => {
  try {
    const { id, ...data } = await request.json();
    if (!id) return new Response(JSON.stringify({ error: 'id required' }), { status: 400 });
    const category = await updateCategory(id, data);
    if (!category) return new Response(JSON.stringify({ error: 'Not found' }), { status: 404 });
    return new Response(JSON.stringify(category), {
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (e: any) {
    return new Response(JSON.stringify({ error: e.message }), { status: 400 });
  }
};

export const DELETE: APIRoute = async ({ request }) => {
  try {
    const { id } = await request.json();
    if (!id) return new Response(JSON.stringify({ error: 'id required' }), { status: 400 });
    const deleted = await deleteCategory(id);
    return new Response(JSON.stringify({ deleted }), {
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (e: any) {
    return new Response(JSON.stringify({ error: e.message }), { status: 400 });
  }
};
