export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import {
  getPendingProposals,
  getProposalStats,
  approveProposal,
  rejectProposal,
  generateProposalsFromPatterns,
} from '@/lib/order-to-cash/self-mod';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const action = searchParams.get('action');

    if (action === 'stats') {
      const stats = await getProposalStats();
      return NextResponse.json(stats);
    }

    if (action === 'generate') {
      const proposalIds = await generateProposalsFromPatterns();
      return NextResponse.json({ generated: proposalIds.length, proposalIds });
    }

    const limit = parseInt(searchParams.get('limit') || '20');
    const proposals = await getPendingProposals(limit);
    
    return NextResponse.json({ proposals });
  } catch (error) {
    console.error('Error fetching self-mod proposals:', error);
    return NextResponse.json({ error: 'Failed to fetch proposals' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const { proposalId, decision, reviewedBy } = await request.json();

    if (!proposalId || !decision || !reviewedBy) {
      return NextResponse.json(
        { error: 'Proposal ID, decision, and reviewer required' },
        { status: 400 }
      );
    }

    if (decision === 'approve') {
      const success = await approveProposal(proposalId, reviewedBy);
      return NextResponse.json({ success, implemented: success });
    } else if (decision === 'reject') {
      await rejectProposal(proposalId, reviewedBy);
      return NextResponse.json({ success: true });
    } else {
      return NextResponse.json(
        { error: 'Decision must be approve or reject' },
        { status: 400 }
      );
    }
  } catch (error) {
    console.error('Error processing self-mod decision:', error);
    return NextResponse.json({ error: 'Failed to process decision' }, { status: 500 });
  }
}
