/**
 * DELETE /api/dashboard/spaces/[id]/share-link/[linkId] — Revoke a space share link.
 *
 * Members can revoke their own links; admins/owners revoke any.
 */

import { requireSession, requireFreshMembership } from '@/lib/auth.js';
import { revokeSpaceShareLink } from '@/lib/space-acl.js';
import { getDb } from '@/lib/db.js';
import { publishStateChanged } from '@/lib/live-events.js';

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

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

    const db = getDb();
    const link = db.prepare('SELECT * FROM space_share_links WHERE id = ? AND space_id = ?').get(linkId, id);
    if (!link) return Response.json({ error: 'Share link not found' }, { status: 404 });

    const isOwner = link.created_by === session.user_id;
    const isAdminOrAbove = session.role === 'admin' || session.role === 'owner';
    if (!isOwner && !isAdminOrAbove) {
      return Response.json({ error: "Cannot revoke another user's share link" }, { status: 403 });
    }

    revokeSpaceShareLink(linkId, session);
    try { publishStateChanged('space_share_links', { space_id: id, link_id: linkId, action: 'revoke' }); } catch { /* observation-only */ }
    return Response.json({ ok: true });
  } catch (err) {
    if (err?.status) return Response.json({ error: err.error || 'error' }, { status: err.status });
    console.error('DELETE /api/dashboard/spaces/[id]/share-link/[linkId] error:', err);
    return Response.json({ error: 'Failed to revoke space share link' }, { status: 500 });
  }
}
