// GET /api/shared/spaces/status?local_space_id=...&space_type=...
// Local-only read of the share ledger — no network. Returns whether a given
// space/project is currently cloud-shared.

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

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

export async function GET(req) {
  try {
    await requireSession(req);
    const { searchParams } = new URL(req.url);
    const localSpaceId = searchParams.get('local_space_id');
    const spaceType = searchParams.get('space_type') || 'dashboard_space';
    if (!localSpaceId) {
      return Response.json({ ok: false, error: 'local_space_id_required' }, { status: 400 });
    }
    const status = getSharedSpaceStatus(localSpaceId, spaceType);
    let cloud_ready = false;
    try { cloud_ready = isSharedCloudReady(); } catch { cloud_ready = false; }
    return Response.json({ ok: true, status, cloud_ready });
  } 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/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 });
  }
}
