import { createApprovalRequest, listApprovalRequests } from '@/lib/approvals.js';

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

export async function GET(req) {
  const { searchParams } = new URL(req.url);
  const status = searchParams.get('status') || undefined;
  const project_id = searchParams.get('project_id') || searchParams.get('project') || undefined;
  const limit = Math.max(1, Math.min(100, Number(searchParams.get('limit') || 50)));
  return Response.json({ ok: true, approvals: listApprovalRequests({ status, project_id, limit }) });
}

export async function POST(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return new Response('Invalid JSON', { status: 400 });
  }
  if (!body?.action_type || !body?.summary) {
    return new Response('action_type and summary are required', { status: 400 });
  }
  const approval = createApprovalRequest({
    action_type: String(body.action_type),
    risk: body.risk || 'medium',
    summary: String(body.summary),
    payload: body.payload || {},
    requested_by: body.requested_by || 'api',
    expires_at: body.expires_at || null,
    project_id: body.project_id || body.project || null,
  });
  return Response.json({ ok: true, approval }, { status: 201 });
}
