/**
 * Pending Approvals API Route
 * GET /api/approvals/pending - List all pending link approvals
 */

import { NextRequest, NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import { AuthMiddleware } from '@/lib/auth';

const prisma = new PrismaClient();

export async function GET(request: NextRequest) {
  try {
    // Require admin role
    const authResult = await AuthMiddleware.requireRole(request, 'ADMIN');
    if (authResult instanceof NextResponse) {
      return authResult;
    }

    // Get all pending link opportunities
    const pendingOpportunities = await prisma.backlinkOpportunity.findMany({
      where: {
        status: 'pending',
      },
      orderBy: [
        { domainAuthority: 'desc' },
        { discoveredAt: 'desc' },
      ],
    });

    // Transform to API format
    const pending = pendingOpportunities.map(opp => ({
      id: opp.id,
      site_id: opp.siteId,
      target_url: opp.targetUrl,
      source_domain: opp.sourceDomain,
      domain_authority: opp.domainAuthority,
      monthly_traffic: opp.monthlyTraffic,
      relevance_score: opp.relevanceScore,
      opportunity_type: opp.opportunityType,
      status: opp.status,
      pitch_draft: opp.pitchDraft,
      contact_email: opp.contactEmail,
      contact_name: opp.contactName,
      discovered_at: opp.discoveredAt.toISOString(),
      notes: opp.notes,
    }));

    return NextResponse.json({
      pending_approvals: pending,
      total: pending.length,
    });
  } catch (error) {
    console.error('[API] Pending approvals error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch pending approvals' },
      { status: 500 }
    );
  }
}
