import { getDb } from '@/lib/db.js';
import { requireSession } from '@/lib/auth.js';
import { assertArtifactAccess } from '@/lib/authz.js';

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

// Returns the raw artifact body so an iframe can `src=`-load it without
// pulling the (often large) HTML into every JSON poll of the case-detail
// page. HTML artifacts are served as `text/html` so the iframe renders
// them directly; everything else returns as `text/plain`.
//
// Raw artifact content is access-controlled. Keep browser caching private so
// ACL or session changes are respected quickly while still avoiding repeated
// iframe fetches during a single viewing session.
export async function GET(req, { params }) {
  try {
    const session = await requireSession(req);
    const { id } = await params;
    if (!id) return new Response('missing_id', { status: 400 });
    const artifact = await assertArtifactAccess(id, session, 'read', req);
    const row = getDb()
      .prepare('SELECT id, kind, content FROM artifacts WHERE id = ? LIMIT 1')
      .get(artifact.id);
    if (!row) return new Response('not_found', { status: 404 });
    // Kinds whose content is a full HTML document. Mines reports emit
    // self-contained HTML under their own kind names, so serve them as
    // text/html too — otherwise the browser shows the raw source as text.
    const HTML_KINDS = new Set(['html', 'mines_investor_presentation', 'mines_project_package']);
    const contentType = HTML_KINDS.has(row.kind) ? 'text/html; charset=utf-8' : 'text/plain; charset=utf-8';
    return new Response(row.content || '', {
      status: 200,
      headers: {
        'content-type': contentType,
        'cache-control': 'private, max-age=300',
        'x-content-type-options': 'nosniff',
      },
    });
  } catch (err) {
    if (err?.status) return new Response(err.error || 'unauthorized', { status: err.status });
    console.error('GET /api/artifacts/[id]/raw error:', err);
    return new Response('failed_to_load_artifact', { status: 500 });
  }
}
