/**
 * Referrals API
 * GET - List referral programs for the authenticated user
 * POST - Create a new referral program
 *
 * All data access goes through Convex. No Prisma fallback.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveOwnerId } from "@/lib/utils/organization-data";
import { CreateReferralSchema } from "@/lib/validators/referrals.validator";
import { logger } from "@/lib/logger";
import { convexQuery, convexMutation } from "@/lib/convex-client";

const log = logger.scope("ReferralsAPI");

function generateReferralCode(): string {
  const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  let code = "REF-";
  for (let i = 0; i < 6; i++) {
    code += chars[Math.floor(Math.random() * chars.length)];
  }
  return code;
}

export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const statusParam = request.nextUrl.searchParams.get("status") ?? undefined;
    const limitParam = request.nextUrl.searchParams.get("limit");
    const limit = limitParam ? parseInt(limitParam, 10) : 50;

    const result = await convexQuery("reviews/referral_queries:getReferrals", {
      userId: user.userId,
      status: statusParam,
      limit,
    });

    return NextResponse.json({
      referrals: result ?? [],
      hasMore: (result ?? []).length >= limit,
      success: true,
    });
  } catch (error) {
    log.error("Failed to list referrals", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const effectiveUserId = await getEffectiveOwnerId(user.userId);
    const body = await request.json();
    const parsed = CreateReferralSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        { success: false, error: parsed.error.flatten() },
        { status: 400 },
      );
    }

    const code = generateReferralCode();

    const referralId = await convexMutation(
      "reviews/referral_mutations:createReferral",
      {
        userId: effectiveUserId,
        code,
        name: parsed.data.name,
        description: parsed.data.description ?? undefined,
        rewardType: parsed.data.rewardType,
        rewardValue: parsed.data.rewardValue,
        rewardCurrency: "QAR",
        maxUses: parsed.data.maxUses ?? undefined,
        expiresAt: parsed.data.expiresAt
          ? new Date(parsed.data.expiresAt).getTime()
          : undefined,
      },
    );

    if (referralId !== null) {
      return NextResponse.json(
        { success: true, referral: { id: referralId, code } },
        { status: 201 },
      );
    }

    return NextResponse.json(
      { success: false, error: "Failed to create referral" },
      { status: 503 },
    );
  } catch (error) {
    log.error("Failed to create referral", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
