/**
 * PATCH /api/artifacts/[id]/protect — toggle is_protected on a single artifact
 *
 * Body: { is_protected: boolean }
 *
 * Guards:
 *   - 404 if artifact does not exist
 *   - 409 if is_protected: true and no privacy_config row exists
 *       (client should open passphrase setup modal then retry)
 */

import { getDb, nowIso } from '@/lib/db.js';
import { appendAudit } from '@/lib/runtime.js';
import { appendProjectChangelog } from '@/lib/projects.js';
import { requireSession } from '@/lib/auth.js';
import { publishStateChanged } from '@/lib/live-events.js';

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

export async function PATCH(req, { params }) {
  const { id } = await params;

  let body;
  try {
    body = await req.json();
  } catch {
    return Response.json({ ok: false, error: 'Invalid JSON' }, { status: 400 });
  }

  if (typeof body?.is_protected !== 'boolean') {
    return Response.json({ ok: false, error: 'is_protected must be a boolean' }, { status: 400 });
  }

  try {
    await requireSession(req);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }

  const is_protected = body.is_protected;

  try {
    const db = getDb();

    // Guard: artifact must exist
    const artifact = db.prepare('SELECT id, project_id, title FROM artifacts WHERE id = ?').get(id);
    if (!artifact) {
      return Response.json({ ok: false, error: 'not_found' }, { status: 404 });
    }

    // Guard: if protecting, privacy_config must be set up first
    if (is_protected) {
      const configCount = db.prepare('SELECT COUNT(*) AS c FROM privacy_config').get();
      if (!configCount || configCount.c === 0) {
        return Response.json({ ok: false, need_passphrase_setup: true }, { status: 409 });
      }
    }

    // Update the flag (SQLite stores booleans as integers)
    db.prepare('UPDATE artifacts SET is_protected = ? WHERE id = ?').run(is_protected ? 1 : 0, id);
    try { publishStateChanged('artifacts', { artifact_id: id, project_id: artifact.project_id, action: 'artifact.protect' }); } catch { /* observation-only */ }

    const auditType = is_protected ? 'privacy.artifact.protect' : 'privacy.artifact.unprotect';
    const summary = is_protected
      ? `Protected artifact ${artifact.title || id}`
      : `Unprotected artifact ${artifact.title || id}`;

    appendAudit({
      type: auditType,
      summary,
      status: 'complete',
      meta: {
        artifact_id: artifact.id,
        project_id: artifact.project_id,
        title: artifact.title,
      },
    });

    // Write project changelog if the helper is available (it is — imported above)
    if (artifact.project_id) {
      appendProjectChangelog(artifact.project_id, {
        action: 'artifact.protect',
        title: summary,
        summary,
        source: 'system',
        details: {
          artifact_id: artifact.id,
          is_protected,
          title: artifact.title,
        },
      });
    }

    return Response.json({
      ok: true,
      artifact_id: artifact.id,
      is_protected: !!is_protected,
    });
  } catch (err) {
    console.error('PATCH /api/artifacts/[id]/protect error:', err);
    return Response.json({ ok: false, error: err.message }, { status: 500 });
  }
}
