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

// GET /api/referrals - Get all referral codes for user
export async function GET(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) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    const referralCodes = await prisma.referralCode.findMany({
      where: { referrerId: user.id },
      include: {
        referrals: {
          include: {
            referralCode: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
    });

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

// POST /api/referrals - Create new referral code
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) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    const body = await req.json();
    const { rewardType, rewardAmount, maxUses, expiresAt } = body;

    // Generate unique code
    const code = `REF-${user.role}-${Math.random().toString(36).substring(2, 10).toUpperCase()}`;

    const referralCode = await prisma.referralCode.create({
      data: {
        code,
        referrerId: user.id,
        referrerType: user.role,
        rewardType: rewardType || 'FIXED_AMOUNT',
        rewardAmount: rewardAmount || 100,
        maxUses,
        expiresAt: expiresAt ? new Date(expiresAt) : undefined,
      },
    });

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