/**
 * DELETE /api/artifacts/[id]/share-link/[linkId] — Revokes a share link.
 *
 * Access rules (from spec):
 *   - Members can revoke their own links.
 *   - Admins and owners can revoke any link.
 */

import { requireSession } from '@/lib/auth.js';
import { assertArtifactAccess } from '@/lib/authz.js';
import { revokeShareLink } from '@/lib/artifact-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);

    // Verify the session can see the artifact.
    await assertArtifactAccess(id, session, 'read', req);

    // Load the link to check ownership.
    const db = getDb();
    const link = db.prepare('SELECT * FROM artifact_share_links WHERE id = ? AND artifact_id = ?').get(linkId, id);
    if (!link) {
      return Response.json({ error: 'Share link not found' }, { status: 404 });
    }

    // Authorization: members can revoke own links; admins/owners revoke any.
    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 });
    }

    revokeShareLink(linkId, session);
    try { publishStateChanged('share_links', { artifact_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/artifacts/[id]/share-link/[linkId] error:', err);
    return Response.json({ error: 'Failed to revoke share link' }, { status: 500 });
  }
}
