import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { findReferrerByCode } from "@/lib/referral";

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { code } = body;

    if (!code || typeof code !== "string") {
      return NextResponse.json(
        { error: "Referral code is required" },
        { status: 400 }
      );
    }

    // Look up the referrer by matching the referral code against all users
    const users = await prisma.user.findMany({
      select: { id: true },
    });

    const referrerId = await findReferrerByCode(users, code);

    if (!referrerId) {
      return NextResponse.json(
        { error: "Invalid referral code" },
        { status: 400 }
      );
    }

    // Save the referral code in a cookie/localStorage so when user registers,
    // the newly created user can be linked. For now, we just create a placeholder
    // "pending" referral. The actual linking happens when the user registers
    // and passes the referral code again (to be paired via the referred user's ID).
    // Since we don't have a "referredId" yet, we store a temporary token.
    const tempToken = `pending_${referrerId}_${Date.now()}`;

    // Store in a lightweight way — we'll use the Referral model with a placeholder referredId
    // The referredId will be updated when registration completes.
    // For production, a ReferralClaimToken model would be better.
    const referral = await prisma.referral.create({
      data: {
        referrerId,
        referredId: `pending_${tempToken}`, // placeholder, will be updated on registration
        status: "pending",
        rewardFlh: 0,
      },
    });

    return NextResponse.json({
      success: true,
      message: "Referral code applied! You'll get 1,000 FLH extra when you sign up, and your referrer earns 200 FLH.",
      referralId: referral.id,
      tempToken,
    });
  } catch (error) {
    console.error("Referral claim error:", error);
    return NextResponse.json(
      { error: "Failed to claim referral" },
      { status: 500 }
    );
  }
}
