/**
 * POST /api/dashboard/spaces/[id]/share-link — Create a public space share link.
 * GET  /api/dashboard/spaces/[id]/share-link — List active links for the space.
 *
 * Auth: requireSession → requireFreshMembership → writer role (owner|admin|member).
 * The grant is the whole space; the public viewer renders its artifacts live.
 */

import { requireSession, requireFreshMembership } from '@/lib/auth.js';
import { createSpaceShareLink, listSpaceShareLinks } from '@/lib/space-acl.js';
import { publishStateChanged } from '@/lib/live-events.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, { params }) {
  try {
    const { id } = await params;
    const session = await requireSession(req);
    await requireFreshMembership(session, session.org_id);
    requireWriter(session);

    const body = await req.json().catch(() => ({}));
    const { expires_in_days, max_views, require_email_otp } = body || {};

    const result = await createSpaceShareLink(
      id,
      {
        expires_in_days: expires_in_days != null ? Number(expires_in_days) : undefined,
        max_views: max_views != null ? Number(max_views) : undefined,
        require_email_otp,
      },
      session
    );
    try { publishStateChanged('space_share_links', { space_id: id, action: 'create' }); } catch { /* observation-only */ }

    return Response.json({ data: result }, { status: 201 });
  } catch (err) {
    if (err?.status) return Response.json({ error: err.error || 'error' }, { status: err.status });
    console.error('POST /api/dashboard/spaces/[id]/share-link error:', err);
    return Response.json({ error: 'Failed to create space share link' }, { status: 500 });
  }
}

export async function GET(req, { params }) {
  try {
    const { id } = await params;
    const session = await requireSession(req);
    await requireFreshMembership(session, session.org_id);
    requireWriter(session);

    return Response.json({ data: listSpaceShareLinks(id) });
  } catch (err) {
    if (err?.status) return Response.json({ error: err.error || 'error' }, { status: err.status });
    console.error('GET /api/dashboard/spaces/[id]/share-link error:', err);
    return Response.json({ error: 'Failed to list space share links' }, { status: 500 });
  }
}
