/**
 * POST /api/artifacts/[id]/share-link — Creates a signed share link.
 * GET  /api/artifacts/[id]/share-link — Lists active share links (admin+ or owner).
 */

import { requireSession, requireFreshMembership } from '@/lib/auth.js';
import { assertArtifactAccess } from '@/lib/authz.js';
import { createShareLink, listShareLinks } from '@/lib/artifact-acl.js';
import { publishStateChanged } from '@/lib/live-events.js';

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

export async function POST(req, { params }) {
  try {
    const { id } = await params;
    const session = await requireSession(req);

    // RD-1: Fresh membership check — sharing is a sensitive action.
    await requireFreshMembership(session, session.org_id);

    // member+ can create share links.
    await assertArtifactAccess(id, session, 'share', req);

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

    const result = await createShareLink(
      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('share_links', { artifact_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/artifacts/[id]/share-link error:', err);
    return Response.json({ error: 'Failed to create share link' }, { status: 500 });
  }
}

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

    // RD-1: Fresh membership check — listing links exposes bearer tokens.
    await requireFreshMembership(session, session.org_id);

    // Share/manage access is required because link rows include bearer tokens.
    await assertArtifactAccess(id, session, 'share', req);

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