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

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

    const userData = await readUserCsv();

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

    const foundUser = findUserByEmail(userData,email)
    if (foundUser && await bcrypt.compare(password, foundUser.password)) {
      console.log("User Details Correct")
      return NextResponse.json({ message: "Login successful!" }, { status: 200 });
    } else {
      console.log("User email or password is invalid")
      return NextResponse.json({ message: "Email and/or password are invalid" }, { status: 401 });
    }


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