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

const VALID_MADHABS = ["Hanafi", "Maliki", "Shafi'i", "Hanbali"];

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

  try {
    const body = await req.json();
    const { name, preferredName, coachPersona, madhab, coachingGoals } = body;

    if (madhab && !VALID_MADHABS.includes(madhab)) {
      return NextResponse.json(
        {
          error: `Invalid madhab. Must be one of: ${VALID_MADHABS.join(", ")}`,
        },
        { status: 400 }
      );
    }

    const updateData: Record<string, string | undefined> = {};
    if (name !== undefined) updateData.name = name;
    if (preferredName !== undefined) updateData.preferredName = preferredName;
    if (coachPersona !== undefined) updateData.coachPersona = coachPersona;
    if (madhab !== undefined) updateData.madhab = madhab;
    if (coachingGoals !== undefined) updateData.coachingGoals = coachingGoals;

    if (Object.keys(updateData).length === 0) {
      return NextResponse.json(
        { error: "No fields to update" },
        { status: 400 }
      );
    }

    const user = await prisma.user.update({
      where: { id: jwtPayload.userId },
      data: updateData,
    });

    return NextResponse.json({
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        isPremium: user.isPremium,
        isPro: user.isPro,
        flhBalance: user.flhBalance,
        dailyMsgCount: user.dailyMsgCount,
        experienceLevel: user.experienceLevel,
        madhab: user.madhab,
        coachPersona: user.coachPersona,
        preferredName: user.preferredName,
        coachingGoals: user.coachingGoals,
        trialEndsAt: user.trialEndsAt,
        createdAt: user.createdAt,
      },
    });
  } catch (error) {
    console.error("Profile update error:", error);
    return NextResponse.json(
      { error: "Profile update failed" },
      { status: 500 }
    );
  }
}
