import { NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import crypto from "node:crypto";
import { prisma } from "@/lib/prisma";
import { sendVerificationEmail } from "@/lib/email";

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

  const name = typeof body.name === "string" ? body.name.trim() : "";
  const email = typeof body.email === "string" ? body.email.toLowerCase().trim() : "";
  const password = typeof body.password === "string" ? body.password : "";

  if (!name || name.length < 2) {
    return NextResponse.json({ error: "Nom trop court (2 car. min)" }, { status: 400 });
  }
  if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    return NextResponse.json({ error: "Email invalide" }, { status: 400 });
  }
  if (password.length < 8) {
    return NextResponse.json({ error: "Mot de passe trop court (8 car. min)" }, { status: 400 });
  }

  const existing = await prisma.user.findUnique({ where: { email } });
  if (existing) {
    return NextResponse.json({ error: "Cet email est déjà utilisé" }, { status: 409 });
  }

  const passwordHash = await bcrypt.hash(password, 12);

  // Split "Prénom Nom" — first word = prénom, rest = nom
  const parts = name.split(" ").filter(Boolean);
  const firstName = parts[0] ?? name;
  const lastName = parts.slice(1).join(" ") || firstName;

  const user = await prisma.user.create({
    data: {
      name,
      email,
      passwordHash,
      plan: "FREE",
      patient: {
        create: { firstName, lastName, email },
      },
    },
  });

  // Create verification token (24h)
  const token = crypto.randomBytes(32).toString("hex");
  await prisma.verifyToken.create({
    data: {
      token,
      userId: user.id,
      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
    },
  });

  try {
    await sendVerificationEmail(email, name, token);
  } catch (e) {
    console.error("[register] email send failed:", e);
    return NextResponse.json(
      { ok: true, emailError: e instanceof Error ? e.message : "Erreur envoi email" },
      { status: 201 }
    );
  }

  return NextResponse.json({ ok: true }, { status: 201 });
}
