import { deleteArtifact } from '@/lib/runtime.js';
import { requireSession } from '@/lib/auth.js';
import { getDb, nowIso } 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 {
    await requireSession(req);
    const { id } = await params;
    const result = deleteArtifact(id);
    if (result.ok) {
      try { publishStateChanged('artifacts', { artifact_id: id, action: 'artifact.delete' }); } catch { /* observation-only */ }
    }
    return Response.json(result, { status: result.ok ? 200 : 404 });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }
}

export async function PATCH(req, { params }) {
  try {
    await requireSession(req);
    const { id } = await params;
    const body = await req.json().catch(() => ({}));
    const db = getDb();
    const row = db.prepare('SELECT id, project_id FROM artifacts WHERE id = ?').get(id);
    if (!row) return Response.json({ error: 'not found' }, { status: 404 });
    if (!Object.prototype.hasOwnProperty.call(body, 'folder_id')) {
      return Response.json({ error: 'no allowed fields supplied' }, { status: 400 });
    }
    let folderId = body.folder_id;
    if (folderId === '' || folderId === undefined) folderId = null;
    if (folderId !== null) {
      const folder = db.prepare('SELECT id FROM disk_folders WHERE id = ? AND project_id = ?').get(folderId, row.project_id);
      if (!folder) return Response.json({ error: 'folder not in this project' }, { status: 400 });
    }
    db.prepare('UPDATE artifacts SET folder_id = ? WHERE id = ?').run(folderId, id);
    const updated = db.prepare('SELECT * FROM artifacts WHERE id = ?').get(id);
    try { publishStateChanged('artifacts', { artifact_id: id, project_id: row.project_id, folder_id: folderId, action: 'artifact.update' }); } catch { /* observation-only */ }
    return Response.json({ artifact: updated, updated_at: nowIso() });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    return Response.json({ error: err?.message || 'patch failed' }, { status: 500 });
  }
}
