// app/api/mines/projects/route.js
//
// GET  — list mines_projects (basic metadata, no pagination needed for small catalog)
// POST — trigger mines_project_create via executeRegistryTool (approval-gated)

import { NextResponse } from 'next/server';
import { executeRegistryTool } from '@/lib/tools/registry.js';
import { requireSession } from '@/lib/auth.js';
import { listMineProjects } from '@/lib/mines/portfolio.js';

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

export async function GET(request) {
  try {
    const data = listMineProjects();
    return NextResponse.json({ data });
  } catch (err) {
    console.error('GET /api/mines/projects error:', err);
    return NextResponse.json({ error: 'Failed to list mine projects' }, { status: 500 });
  }
}

export async function POST(request) {
  let body;
  try {
    body = await request.json().catch(() => ({}));
  } catch {
    body = {};
  }

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

  const result = await executeRegistryTool(
    'mines_project_create',
    {
      name:               body?.name || null,
      slug:               body?.slug || null,
      asset_stage:        body?.asset_stage || null,
      commodity:          body?.commodity || null,
      deposit_type:       body?.deposit_type || null,
      portfolio_entry_id: body?.portfolio_entry_id || null,
      description:        body?.description || null,
      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',
    }
  );

  return NextResponse.json(result);
}
