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

// POST /api/referrals/track - Track referral conversion
export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { referralCode, referredUserId, leadId, quoteId, contractId } = body;

    if (!referralCode || !referredUserId) {
      return NextResponse.json(
        { error: 'Referral code and referred user ID are required' },
        { status: 400 }
      );
    }

    // Find the referral code
    const code = await prisma.referralCode.findUnique({
      where: { code: referralCode },
    });

    if (!code) {
      return NextResponse.json({ error: 'Invalid referral code' }, { status: 404 });
    }

    if (!code.isActive) {
      return NextResponse.json({ error: 'Referral code is inactive' }, { status: 400 });
    }

    if (code.expiresAt && new Date() > code.expiresAt) {
      return NextResponse.json({ error: 'Referral code has expired' }, { status: 400 });
    }

    if (code.maxUses && code.timesUsed >= code.maxUses) {
      return NextResponse.json({ error: 'Referral code usage limit reached' }, { status: 400 });
    }

    // Determine status based on conversion stage
    let status: any = 'PENDING';
    if (contractId) status = 'CONTRACT_SIGNED';
    else if (quoteId) status = 'QUOTE_SENT';
    else if (leadId) status = 'LEAD_CREATED';

    // Create referral record
    const referral = await prisma.referral.create({
      data: {
        referralCodeId: code.id,
        referrerId: code.referrerId,
        referredUserId,
        status,
        leadId,
        quoteId,
        contractId,
        convertedAt: contractId ? new Date() : undefined,
      },
    });

    // Update referral code usage
    await prisma.referralCode.update({
      where: { id: code.id },
      data: {
        timesUsed: { increment: 1 },
        conversions: contractId ? { increment: 1 } : undefined,
      },
    });

    return NextResponse.json({ referral, message: 'Referral tracked successfully' });
  } catch (error) {
    console.error('Error tracking referral:', error);
    return NextResponse.json(
      { error: 'Failed to track referral' },
      { status: 500 }
    );
  }
}
