
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { prisma } from '@/lib/db';

// GET /api/recovery-campaigns - Get recovery campaigns
export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const campaigns = await prisma.recoveryCampaign.findMany({
      orderBy: { createdAt: 'desc' },
    });

    return NextResponse.json({ campaigns });
  } catch (error) {
    console.error('Error fetching recovery campaigns:', error);
    return NextResponse.json(
      { error: 'Failed to fetch recovery campaigns' },
      { status: 500 }
    );
  }
}

// POST /api/recovery-campaigns - Create recovery campaign
export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await req.json();
    const {
      name,
      description,
      targetRejectionReasons,
      targetRegions,
      minQuoteValue,
      maxDaysSinceRejection,
      emailTemplate,
      discountOffer,
      status,
      scheduledFor,
    } = body;

    if (!name || !emailTemplate) {
      return NextResponse.json(
        { error: 'Name and email template are required' },
        { status: 400 }
      );
    }

    const campaign = await prisma.recoveryCampaign.create({
      data: {
        name,
        description,
        targetRejectionReasons: targetRejectionReasons || [],
        targetRegions: targetRegions || [],
        minQuoteValue,
        maxDaysSinceRejection,
        emailTemplate,
        discountOffer,
        status: status || 'DRAFT',
        scheduledFor: scheduledFor ? new Date(scheduledFor) : undefined,
      },
    });

    return NextResponse.json({ campaign }, { status: 201 });
  } catch (error) {
    console.error('Error creating recovery campaign:', error);
    return NextResponse.json(
      { error: 'Failed to create recovery campaign' },
      { status: 500 }
    );
  }
}
