import { requireFreshMembership, requireSession } from '@/lib/auth.js';
import { requireRole } from '@/lib/authz.js';
import {
  approveMinesImportRoot,
  listMinesImportRoots,
  removeMinesImportRoot,
} from '@/lib/mines/import-roots.js';

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

async function requireAdmin(request) {
  const session = await requireSession(request);
  await requireFreshMembership(session, session.org_id);
  requireRole(session, 'admin', session.org_id);
  return session;
}

function authError(err) {
  if (err && typeof err === 'object' && err.status) {
    return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
  }
  throw err;
}

export async function GET(request) {
  try {
    const session = await requireAdmin(request);
    return Response.json({ status: 'ok', roots: listMinesImportRoots({ org_id: session.org_id }) });
  } catch (err) {
    return authError(err);
  }
}

export async function POST(request) {
  let session;
  try {
    session = await requireAdmin(request);
  } catch (err) {
    return authError(err);
  }

  const body = await request.json().catch(() => ({}));
  const result = approveMinesImportRoot(body?.directory_path || body?.directory_root || body?.root_path, {
    label: body?.label || null,
    user_id: session.user_id,
    org_id: session.org_id,
    acting_on_behalf_of_user_id: session.user_id,
  });
  const status = result.status === 'ok' ? 200 : 400;
  return Response.json(result, { status });
}

export async function DELETE(request) {
  let session;
  try {
    session = await requireAdmin(request);
  } catch (err) {
    return authError(err);
  }

  const { searchParams } = new URL(request.url);
  const result = removeMinesImportRoot(searchParams.get('id'), {
    user_id: session.user_id,
    org_id: session.org_id,
    acting_on_behalf_of_user_id: session.user_id,
  });
  const status = result.status === 'ok' ? 200 : 404;
  return Response.json(result, { status });
}
