import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { DIABETES_TYPE_VALUES, SEX_VALUES } from "@/lib/patient";

export async function GET() {
  const session = await auth();
  if (!session?.user?.id) return NextResponse.json({ error: "Non authentifié" }, { status: 401 });

  const patient = await prisma.patient.findUnique({ where: { userId: session.user.id } });
  return NextResponse.json(patient);
}

export async function PUT(request: Request) {
  const session = await auth();
  if (!session?.user?.id) return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
  const userId = session.user.id;

  const body = await request.json().catch(() => null);
  if (!body) return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });

  const firstName = typeof body.firstName === "string" ? body.firstName.trim() : "";
  const lastName = typeof body.lastName === "string" ? body.lastName.trim() : "";
  if (!firstName || !lastName) {
    return NextResponse.json({ error: "Nom et prénom requis" }, { status: 400 });
  }

  const email =
    typeof body.email === "string" && body.email.trim() ? body.email.trim() : null;
  const birthDate =
    typeof body.birthDate === "string" && body.birthDate ? new Date(body.birthDate) : null;

  const heightCm =
    body.heightCm === "" || body.heightCm == null ? null : Math.round(Number(body.heightCm));
  if (heightCm !== null && (!Number.isFinite(heightCm) || heightCm < 50 || heightCm > 260)) {
    return NextResponse.json({ error: "Taille invalide (50–260 cm)" }, { status: 400 });
  }

  const weightKg =
    body.weightKg === "" || body.weightKg == null
      ? null
      : Math.round(Number(body.weightKg) * 10) / 10;
  if (weightKg !== null && (!Number.isFinite(weightKg) || weightKg < 20 || weightKg > 400)) {
    return NextResponse.json({ error: "Poids invalide (20–400 kg)" }, { status: 400 });
  }

  const sex =
    typeof body.sex === "string" && SEX_VALUES.includes(body.sex) ? body.sex : null;
  const diabetesType =
    typeof body.diabetesType === "string" && DIABETES_TYPE_VALUES.includes(body.diabetesType)
      ? body.diabetesType
      : null;
  const treatment =
    typeof body.treatment === "string" && body.treatment.trim() ? body.treatment.trim() : null;
  if (treatment !== null && treatment.length > 1000) {
    return NextResponse.json({ error: "Traitement trop long (1000 car. max)" }, { status: 400 });
  }

  const data = { firstName, lastName, email, birthDate, heightCm, weightKg, sex, diabetesType, treatment };

  const patient = await prisma.patient.upsert({
    where: { userId },
    create: { userId, ...data },
    update: data,
  });

  return NextResponse.json(patient);
}
