// /src/app/api/managers/route.ts

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import bcrypt from "bcrypt";

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const { email, password, firstName, lastName, phone, address, city, country } = body;

    if (!email || !password || !firstName || !lastName || !phone || !address || !city || !country) {
      return NextResponse.json({ message: "Tous les champs sont requis." }, { status: 400 });
    }

    const existingUser = await prisma.user.findUnique({ where: { email } });
    if (existingUser) {
      return NextResponse.json({ message: "Cet email est déjà utilisé." }, { status: 409 });
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    const newManager = await prisma.user.create({
      data: {
        email,
        password: hashedPassword,
        firstName,
        lastName,
        phone,
        address,
        city,
        country,
        role: "MANAGER",
      },
    });
   
    return NextResponse.json(newManager, { status: 201 });
  } catch (error) {
    console.error("Erreur POST /api/managers:", error);
    return NextResponse.json({ message: "Erreur interne du serveur." }, { status: 500 });
  }
}
