import connect from "@/config/config";
import User from "@/models/user";
import { NextResponse } from "next/server";
import bcryptjs from "bcryptjs";
connect();
export async function POST(request) {
try {
const reqBody = await request.json();
const { name, email, password } = reqBody;
if (!name || !email || !password) {
return NextResponse.json(
{ error: "All fields (name, email, password) are required", success: false },
{ status: 400 }
);
}
const user = await User.findOne({ email });
if (user) {
return NextResponse.json(
{ error: "User already exists", success: false },
{ status: 400 }
);
}
const salt = await bcryptjs.genSalt(10);
const hashedPassword = await bcryptjs.hash(password, salt);
const newUser = new User({
name,
email,
password: hashedPassword,
});
const savedUser = await newUser.save();
return NextResponse.json(
{
message: "User created successfully",
success: true,
user: savedUser,
},
{ status: 201 }
);
} catch (error) {
console.error("Error while creating user:", error.message);
return NextResponse.json(
{ error: "Internal Server Error", success: false },
{ status: 500 }
);
}
}