import {
  getSpace,
  renameSpace,
  setActiveSpace,
  deleteSpace,
} from '../../../../../lib/dashboard-spaces.js';

export async function GET(_request, { params }) {
  try {
    const { id } = await params;
    const space = getSpace(id);
    if (!space) return Response.json({ error: 'Not found' }, { status: 404 });
    return Response.json({ space });
  } catch (err) {
    return Response.json({ error: err?.message || String(err) }, { status: 500 });
  }
}

export async function PATCH(request, { params }) {
  try {
    const { id } = await params;
    const body = await request.json().catch(() => ({}));
    let space = getSpace(id);
    if (!space) return Response.json({ error: 'Not found' }, { status: 404 });
    if (typeof body?.name === 'string') space = renameSpace(id, body.name);
    if (body?.is_active === true) space = setActiveSpace(id);
    return Response.json({ space });
  } catch (err) {
    const status = err?.code === 'SPACE_NOT_FOUND' ? 404 : 400;
    return Response.json({ error: err?.message || String(err), code: err?.code }, { status });
  }
}

export async function DELETE(_request, { params }) {
  try {
    const { id } = await params;
    const result = deleteSpace(id);
    if (!result) return Response.json({ error: 'Not found' }, { status: 404 });
    return Response.json(result);
  } catch (err) {
    const status = err?.code === 'SPACE_LAST' ? 409 : 400;
    return Response.json({ error: err?.message || String(err), code: err?.code }, { status });
  }
}
