import { NextRequest, NextResponse } from "next/server";
import { requireAuth } from "@/lib/auth";
import { encodeReferralCode } from "@/lib/referral";

export async function GET(req: NextRequest) {
  const jwtPayload = await requireAuth(req);
  if (!jwtPayload) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const referralCode = encodeReferralCode(jwtPayload.userId);

    return NextResponse.json({
      referralCode,
      shareLink: `${process.env.NEXT_PUBLIC_APP_URL || "https://falahos.my/mobile"}/auth?ref=${referralCode}`,
    });
  } catch (error) {
    console.error("Referral code error:", error);
    return NextResponse.json(
      { error: "Failed to generate referral code" },
      { status: 500 }
    );
  }
}
