// POST /api/shared/spaces/publish — explicitly share a dashboard space OR a
// project folder into the org's cloud shared layer.
//
// Body:
//   { space_type: 'dashboard_space', space_id, visibility? }
//   { space_type: 'project', project_id | slug, visibility?, include_resource_metadata? }
//
// Server-only: routes through lib/shared-cloud.js, which holds the service-role
// key and never ships it to the browser. Sharing is always explicit + audited.

import {
  publishDashboardSpace,
  publishProjectFolder,
  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 (!isSharedCloudReady()) {
      return Response.json({ ok: false, error: 'shared_cloud_not_configured' }, { status: 503 });
    }

    const space_type = body?.space_type || 'dashboard_space';
    const visibility = body?.visibility || 'org';

    let status;
    if (space_type === 'project') {
      const idOrSlug = body?.project_id || body?.slug;
      if (!idOrSlug) {
        return Response.json({ ok: false, error: 'project_id_or_slug_required' }, { status: 400 });
      }
      status = await publishProjectFolder({
        project_id: body.project_id,
        slug: body.slug,
        session,
        visibility,
        includeResourceMetadata: body?.include_resource_metadata !== false,
        includeLocalOnly: body?.include_local_only === true,
        allowLocalOnlyOverride: body?.allow_local_only_override === true,
        published_by: session.user_id,
      });
    } else if (space_type === 'dashboard_space') {
      if (!body?.space_id) {
        return Response.json({ ok: false, error: 'space_id_required' }, { status: 400 });
      }
      status = await publishDashboardSpace({
        space_id: body.space_id,
        session,
        visibility,
        published_by: session.user_id,
      });
    } else {
      return Response.json({ ok: false, error: 'invalid_space_type' }, { status: 400 });
    }

    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 });
    }
    // Validation errors from the mappers surface as 400; everything else 500.
    if (/invalid (visibility|space_type)|required|not found|refusing to share/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 });
  }
}
