import type { APIRoute } from 'astro';
import { listCollections, createCollection, updateCollection, deleteCollection } from '../../../lib/collections/collection-manager.js';

export const GET: APIRoute = async () => {
  try {
    const collections = await listCollections({ activeOnly: false });
    return new Response(JSON.stringify({ collections }), {
      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 collection = await createCollection(data);
    return new Response(JSON.stringify(collection), {
      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 collection = await updateCollection(id, data);
    if (!collection) return new Response(JSON.stringify({ error: 'Not found' }), { status: 404 });
    return new Response(JSON.stringify(collection), {
      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 deleteCollection(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 });
  }
};
