// app/api/mines/projects/[id]/import/route.js
//
// POST — trigger mines_data_import via executeRegistryTool (high-risk,
//        approval-gated for non-owners). [id] is the mines_projects.id.
// GET  — import progress: { total_files, queued, running, complete, failed, skipped }

import { NextResponse } from 'next/server';
import { executeRegistryTool } from '@/lib/tools/registry.js';
import { requireFreshMembership, requireSession } from '@/lib/auth.js';
import { requireRole } from '@/lib/authz.js';
import { getImportProgress } from '@/lib/mines/data-quality.js';
import { assertMinesProjectForOrg } from '@/lib/mines/project-auth.js';

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

export async function GET(request, { params }) {
  const { id } = await params;
  let session;
  try {
    session = await requireSession(request);
    await requireFreshMembership(session, session.org_id);
    requireRole(session, 'viewer', session.org_id);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return NextResponse.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }

  try {
    const projectAccess = assertMinesProjectForOrg(id, session.org_id);
    if (!projectAccess.ok) {
      return NextResponse.json({ error: projectAccess.error }, { status: 404 });
    }
    const progress = getImportProgress(id);
    return NextResponse.json({ data: progress });
  } catch (err) {
    console.error('GET /api/mines/projects/[id]/import error:', err);
    return NextResponse.json({ error: 'Failed to read import progress' }, { status: 500 });
  }
}

export async function POST(request, { params }) {
  const { id } = await params;

  let body;
  try {
    body = await request.json().catch(() => ({}));
  } catch {
    body = {};
  }

  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 projectAccess = assertMinesProjectForOrg(id, session.org_id);
  if (!projectAccess.ok) {
    return NextResponse.json({ error: projectAccess.error }, { status: 404 });
  }

  const result = await executeRegistryTool(
    'mines_data_import',
    {
      project_id: id,
      directory_path: body?.directory_path || body?.directory_root || null,
      resume: body?.resume ?? false,
      approval_id: body?.approval_id || null,
    },
    {
      user_id: session.user_id,
      acting_on_behalf_of_user_id: session.user_id,
      owner_trusted: session.role === 'owner' || session.role === 'admin',
      org_id: session.org_id,
      actor_role: session.role,
    }
  );

  return NextResponse.json(result);
}
