// POST /api/shared/spaces/unpublish — explicitly unshare a dashboard space or
// project folder. Removes the cloud rows and flips the local ledger. The local
// space/project itself is never touched.
//
// Body: { local_space_id, space_type? }

import { unpublishSpace, isSharedCloudReady } from '../../../../../lib/shared-cloud.js';
import { requireSession, requireFreshMembership } from '../../../../../lib/auth.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

function requireWriter(session) {
  if (!['owner', 'admin', 'member'].includes(session.role)) {
    throw { status: 403, error: 'forbidden' };
  }
}

export async function POST(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return Response.json({ ok: false, error: 'invalid_json' }, { status: 400 });
  }

  try {
    const session = await requireSession(req);
    await requireFreshMembership(session, session.org_id);
    requireWriter(session);

    if (!body?.local_space_id) {
      return Response.json({ ok: false, error: 'local_space_id_required' }, { status: 400 });
    }
    if (!isSharedCloudReady()) {
      return Response.json({ ok: false, error: 'shared_cloud_not_configured' }, { status: 503 });
    }

    const status = await unpublishSpace({
      local_space_id: body.local_space_id,
      space_type: body.space_type || 'dashboard_space',
      session,
    });

    return Response.json({ ok: true, status }, { status: 200 });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ ok: false, error: err.error || 'unauthorized' }, { status: err.status });
    }
    if (/invalid space_type|required/i.test(String(err?.message || ''))) {
      return Response.json({ ok: false, error: err.message }, { status: 400 });
    }
    return Response.json({ ok: false, error: err?.message || 'server_error' }, { status: 500 });
  }
}
