/**
 * Approval Action API Route
 * POST /api/approvals/[id]/action - Approve or reject a link opportunity
 */

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

const prisma = new PrismaClient();

interface ActionBody {
  action: 'approve' | 'reject';
  reason?: string;
  edited_pitch?: string;
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // Require admin role
    const authResult = await AuthMiddleware.requireRole(request, 'ADMIN');
    if (authResult instanceof NextResponse) {
      return authResult;
    }

    const { id } = await params;
    const body: ActionBody = await request.json();

    if (!body.action || !['approve', 'reject'].includes(body.action)) {
      return NextResponse.json(
        { error: 'Invalid action. Must be "approve" or "reject"' },
        { status: 400 }
      );
    }

    // Find the opportunity
    const opportunity = await prisma.backlinkOpportunity.findUnique({
      where: { id },
    });

    if (!opportunity) {
      return NextResponse.json(
        { error: 'Opportunity not found' },
        { status: 404 }
      );
    }

    if (opportunity.status !== 'pending') {
      return NextResponse.json(
        { error: `Cannot ${body.action} - opportunity is already ${opportunity.status}` },
        { status: 400 }
      );
    }

    const now = new Date();

    if (body.action === 'approve') {
      await prisma.backlinkOpportunity.update({
        where: { id },
        data: {
          status: 'approved',
          approvedAt: now,
          approvedBy: authResult.user?.email || 'admin',
          pitchApproved: body.edited_pitch || opportunity.pitchDraft,
          updatedAt: now,
        },
      });

      await ComplianceService.log('AGENT', 'LINK_OPPORTUNITY_APPROVED', 'ApprovalsAPI', {
        opportunityId: id,
        domain: opportunity.sourceDomain,
        domainAuthority: opportunity.domainAuthority,
        approvedBy: authResult.user?.email,
      });

      return NextResponse.json({
        opportunity_id: id,
        status: 'approved',
        message: 'Link opportunity approved',
      });
    }

    if (body.action === 'reject') {
      if (!body.reason) {
        return NextResponse.json(
          { error: 'Rejection reason is required' },
          { status: 400 }
        );
      }

      await prisma.backlinkOpportunity.update({
        where: { id },
        data: {
          status: 'rejected',
          rejectionReason: body.reason,
          updatedAt: now,
        },
      });

      await ComplianceService.log('AGENT', 'LINK_OPPORTUNITY_REJECTED', 'ApprovalsAPI', {
        opportunityId: id,
        domain: opportunity.sourceDomain,
        reason: body.reason,
      });

      return NextResponse.json({
        opportunity_id: id,
        status: 'rejected',
        message: `Link opportunity rejected: ${body.reason}`,
      });
    }

    return NextResponse.json(
      { error: 'Invalid action' },
      { status: 400 }
    );
  } catch (error) {
    console.error('[API] Approval action error:', error);
    return NextResponse.json(
      { error: 'Failed to process approval action' },
      { status: 500 }
    );
  }
}
