// pages/api/referral/signup.ts
import { NextRequest, NextResponse } from "next/server";
import dbConnect from "@/lib/connectdb";
import { User } from "@/models/user";
import { Referral } from "@/models/user";

export async function POST(req: NextRequest) {
  try {
    const { email, referralCode } = await req.json();
    await dbConnect();

    // Find the referrer
    const referrer = await User.findOne({ referralCode });
    if (!referrer) {
      return NextResponse.json(
        { error: "Invalid referral code" },
        { status: 400 }
      );
    }

    // Create the new user
    const newUser = await User.create({
      email,
      referredBy: referrer._id, // Associate the new user with the referrer
    });

    // Track the referral
    await Referral.create({
      referrerId: referrer._id,
      referredId: newUser._id,
    });

    return NextResponse.json(
      { message: "User created successfully", user: newUser },
      { status: 201 }
    );
  } catch (error) {
    return NextResponse.json({ error: "Server error" }, { status: 500 });
  }
}
