/**
 * GET  /api/artifacts/[id]/acl — Returns the current ACL for an artifact.
 * PUT  /api/artifacts/[id]/acl — Updates the ACL scope (admin+ only, RD-1 fresh check).
 */

import { requireSession, requireFreshMembership } from '@/lib/auth.js';
import { assertArtifactAccess, requireRole } from '@/lib/authz.js';
import { getAcl, setAcl } from '@/lib/artifact-acl.js';
import { appendComplianceAudit, ComplianceActions, requestIp, requestUserAgent } from '@/lib/compliance-audit.js';
import { publishStateChanged } from '@/lib/live-events.js';

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

export async function GET(req, { params }) {
  try {
    const { id } = await params;
    const session = await requireSession(req);
    await assertArtifactAccess(id, session, 'read', req);
    const acl = getAcl(id);
    return Response.json({ data: acl });
  } catch (err) {
    if (err?.status) {
      return Response.json({ error: err.error || 'error' }, { status: err.status });
    }
    console.error('GET /api/artifacts/[id]/acl error:', err);
    return Response.json({ error: 'Failed to fetch ACL' }, { status: 500 });
  }
}

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

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

    // Only admins and owners may update ACLs.
    requireRole(session, 'admin');

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

    const body = await req.json();
    const { scope, team_id } = body || {};

    if (!scope) {
      return Response.json({ error: 'scope is required' }, { status: 400 });
    }

    const acl = setAcl(id, { scope, team_id, updated_by: session.user_id });
    try { publishStateChanged('acl', { artifact_id: id, scope, team_id: team_id || null }); } catch { /* observation-only */ }

    // Compliance audit.
    try {
      appendComplianceAudit({
        user_id: session.user_id,
        org_id: session.org_id,
        action: ComplianceActions.ARTIFACT_ACL_UPDATED,
        action_target_id: id,
        action_target_type: 'artifact',
        status: 'success',
        summary: `ACL updated to '${scope}' for artifact ${id}`,
        meta: { scope, team_id: team_id || null, previous_scope: null },
        ip: requestIp(req),
        user_agent: requestUserAgent(req),
      });
    } catch (auditErr) {
      console.error('PUT /api/artifacts/[id]/acl audit error:', auditErr.message);
    }

    return Response.json({ data: acl });
  } catch (err) {
    if (err?.status) {
      return Response.json({ error: err.error || 'error' }, { status: err.status });
    }
    console.error('PUT /api/artifacts/[id]/acl error:', err);
    return Response.json({ error: 'Failed to update ACL' }, { status: 500 });
  }
}
