// app/api/mines/portfolio/route.js
//
// GET  — list portfolio entries with filters + pagination
// POST — trigger mines_catalog_import via executeRegistryTool (approval-gated)

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

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

export async function GET(request) {
  try {
    const { searchParams } = new URL(request.url);

    const opts = {
      commodity:         searchParams.get('commodity') || undefined,
      deposit_type:      searchParams.get('deposit_type') || undefined,
      has_drilling:      searchParams.get('has_drilling') || undefined,
      data_completeness: searchParams.get('data_completeness') || undefined,
      sort:              searchParams.get('sort') || 'name',
      limit:             parseInt(searchParams.get('limit') || '50', 10),
      offset:            parseInt(searchParams.get('offset') || '0', 10),
    };

    const result = listPortfolioEntries(opts);
    return NextResponse.json(result);
  } catch (err) {
    console.error('GET /api/mines/portfolio error:', err);
    return NextResponse.json({ error: 'Failed to list portfolio entries' }, { status: 500 });
  }
}

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

  // Resolve session for owner_trusted / user_id propagation.
  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;
  }

  // Always goes through executeRegistryTool so the approval gate fires.
  // The caller must supply approval_id on the second call to proceed.
  const result = await executeRegistryTool(
    'mines_catalog_import',
    {
      file_id:        body?.file_id || null,
      portfolio_name: body?.portfolio_name || null,
      sheet_name:     body?.sheet_name || 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);
}
