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

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

    const { searchParams } = new URL(req.url);
    const channel = searchParams.get('channel');
    const isActive = searchParams.get('isActive');

    const where: any = {};
    if (channel) {
      where.channel = channel;
    }
    if (isActive !== null) {
      where.isActive = isActive === 'true';
    }

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

    // Calculate metrics
    const campaignsWithMetrics = campaigns.map((campaign: any) => {
      const cpc = campaign.clicks > 0 ? campaign.spent / campaign.clicks : 0;
      const cpl = campaign.leads > 0 ? campaign.spent / campaign.leads : 0;
      const cpa = campaign.conversions > 0 ? campaign.spent / campaign.conversions : 0;
      const roas = campaign.spent > 0 ? (campaign.revenue / campaign.spent) * 100 : 0;
      const roi = campaign.spent > 0 ? ((campaign.revenue - campaign.spent) / campaign.spent) * 100 : 0;

      return {
        ...campaign,
        cpc: parseFloat(cpc.toFixed(2)),
        cpl: parseFloat(cpl.toFixed(2)),
        cpa: parseFloat(cpa.toFixed(2)),
        roas: parseFloat(roas.toFixed(2)),
        roi: parseFloat(roi.toFixed(2)),
      };
    });

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

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

    const user = await prisma.user.findUnique({
      where: { email: session.user.email },
    });

    if (!user || (user.role !== 'ADMIN' && user.role !== 'SALES')) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 403 });
    }

    const body = await req.json();
    const {
      name,
      description,
      channel,
      platform,
      budget,
      trackingCode,
      utmSource,
      utmMedium,
      utmCampaign,
      startDate,
      endDate,
    } = body;

    if (!name || !channel || !budget || !trackingCode || !startDate) {
      return NextResponse.json(
        { error: 'Name, channel, budget, tracking code, and start date are required' },
        { status: 400 }
      );
    }

    const campaign = await prisma.marketingCampaign.create({
      data: {
        name,
        description,
        channel,
        platform,
        budget,
        trackingCode,
        utmSource,
        utmMedium,
        utmCampaign,
        startDate: new Date(startDate),
        endDate: endDate ? new Date(endDate) : undefined,
      },
    });

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