import { NextResponse } from "next/server";
import {User, readUserCsv, writeUserCsv, findUserByEmail, passwordStrengthCheck} from "../functions/csvReadWrite";
import bcrypt from "bcrypt"

export async function POST(request: Request) {
  try {
    const body = await request.json(); // Parse incoming JSON data
    let {name, email, password } = body;
    const accessLevel = "basic";
    console.log("Signin API received data"); 

    const userData = await readUserCsv();

    console.log(userData)
    console.log("Name:", name); // ! remove
    console.log("Email:", email); // ! remove
    console.log("Password:", password);// ! remove

    const foundUser = findUserByEmail(userData,email)

    if (foundUser) {
      console.log("Email already in the system")
      return NextResponse.json({ message: "Sorry, this email is already in use" }, { status: 409 });
    }

    const passwordCheckResult = await passwordStrengthCheck(password)
    
    if (passwordCheckResult === "short"){
      return NextResponse.json({ message: "Your password is shorter than 8 characters" }, { status: 400 });
    } else if (passwordCheckResult === "long"){
      return NextResponse.json({ message: "Your password is longer than 16 characters" }, { status: 400 });
    } else if (passwordCheckResult === "no lower"){
      return NextResponse.json({ message: "Your password must contain a lowercase letters" }, { status: 400 });
    } else if (passwordCheckResult === "no upper"){
      return NextResponse.json({ message: "Your password must contain a uppercase letters" }, { status: 400 });
    } else if (passwordCheckResult === "no digit"){
      return NextResponse.json({ message: "Your password must contain a number" }, { status: 400 });
    } else if (passwordCheckResult === "no special"){
      return NextResponse.json({ message: "Your password must contain a special character (!@#$%^&*)" }, { status: 400 });
    } else if (passwordCheckResult === "end of function"){
      return NextResponse.json({ message: "Password check script failure" }, { status: 500 });
    } else {
      try {
        password = await bcrypt.hash(password, 10);
        userData.push({name,email,password,accessLevel})
        await writeUserCsv(userData)
        return NextResponse.json({ message: "Account Created" }, { status: 201 });
      } catch(error) {
        console.error("Error in writting :", error);
      return NextResponse.json({ message: "Internal Server Error" }, { status: 500 });
      }
    }


  } catch (error) {
    console.error("Error in signup endpoint:", error);
    return NextResponse.json({ message: "Internal Server Error" }, { status: 500 });
  }
}