import { response } from "@/lib/helperFunction";
import { initDb } from "@/lib/init";
import { loginSchema } from "@/lib/loginSchema";
import User from "@/models/User";
import { NextResponse } from "next/server";

import bcrypt from "bcryptjs";
export async function POST(req) {
  try {
    await initDb();
    // verify request payload(coming from frontend) in backend
    const validationSchema = loginSchema.pick(["name", "email", "password"]);
    const payload = await req.json();
    console.log("data received", payload);
    //const validatedData = validationSchema.validate(payload.)
    const validatedData = await validationSchema.validate(payload, {
      abortEarly: false,
    });

    //console.log("Validate Data :",validatedData)
    if (!validatedData) {
      return response(
        false,
        401,
        "Invalid / Missing input fields",
        validatedData.error
      );
    }

    // if data is valid, then follow

    const { name, email, password } = validatedData; // destruction of validatedData
    //console.log(name)

    // check already registered email
    const checkUserEmail = await User.findOne({ where: { email: email } }); // Using a criteria
    //console.log(checkUserEmail)
    if (checkUserEmail) {
      return response(false, 409, "User Already registered", checkUserEmail);
    }

    // new registration
    const hashPassword = await bcrypt.hash(password, 12);
    const newUser = await User.create({
      name: name,
      email: email,
      password: hashPassword,
    });
    console.log(`Inserted Record Id ${newUser.id}`); // display the inserted record id
    //res.status(200).json({ data: newUser });
    console.log(newUser);
    //res.end();

    return response(true, 200, "Valid Data", newUser);
  } catch (error) {}
}
