// app/api/mines/projects/[id]/publish/route.js
//
// POST — publish a Mines project's diligence artifacts to a dashboard space.
//   1. Set the project's default_space_id (so future agent/manual generations
//      land in the same space).
//   2. Generate the whole-page project_package artifact (pinned to the space).
//   3. Pin every existing artifact for the project into the space so they all
//      surface as windows on the dashboard board.
//
// Body: { space_id }  ([id] is the mines_projects.id)

import { NextResponse } from 'next/server';
import { getDb, nowIso } from '@/lib/db.js';
import { requireFreshMembership, requireSession } from '@/lib/auth.js';
import { requireRole } from '@/lib/authz.js';
import { assertMinesProjectForOrg } from '@/lib/mines/project-auth.js';
import { getSpace, moveArtifactToSpace } from '@/lib/dashboard-spaces.js';
import { minesReportGenerate } from '@/lib/tools/adapters/mines/report-generate.js';

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

export async function POST(request, { params }) {
  const { id } = await params;
  const body = await request.json().catch(() => ({}));
  const spaceId = body?.space_id;

  let session;
  try {
    session = await requireSession(request);
    await requireFreshMembership(session, session.org_id);
    requireRole(session, 'admin', session.org_id);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return NextResponse.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }

  const access = assertMinesProjectForOrg(id, session.org_id);
  if (!access.ok) return NextResponse.json({ error: access.error }, { status: 404 });

  if (!spaceId || !getSpace(spaceId)) {
    return NextResponse.json({ error: 'invalid_space_id' }, { status: 400 });
  }

  const db = getDb();
  const project = db.prepare('SELECT id, os_project_id FROM mines_projects WHERE id = ?').get(id);
  if (!project) return NextResponse.json({ error: 'project_not_found' }, { status: 404 });

  // 1. Persist the project's default space.
  db.prepare('UPDATE mines_projects SET default_space_id = ?, updated_at = ? WHERE id = ?')
    .run(spaceId, nowIso(), id);

  // 2. Generate the whole-page package artifact (resolves + pins the space itself).
  let packageArtifactId = null;
  try {
    const res = await minesReportGenerate(
      { project_id: id, report_kind: 'project_package', space_id: spaceId },
      { agent_id: 'mines-report-packager', user_id: session.user_id, acting_on_behalf_of_user_id: session.user_id }
    );
    if (res.status === 'ok') packageArtifactId = res.artifact_id;
  } catch { /* non-fatal — still pin existing artifacts */ }

  // 3. Pin every existing artifact for the project into the space.
  const rows = db.prepare(
    'SELECT id FROM artifacts WHERE project_id IN (?, ?)'
  ).all(id, project.os_project_id || '');
  let pinned = 0;
  for (const r of rows) {
    try { moveArtifactToSpace(r.id, spaceId); pinned += 1; } catch { /* skip */ }
  }

  return NextResponse.json({
    data: { space_id: spaceId, package_artifact_id: packageArtifactId, pinned_artifacts: pinned },
  });
}
