import bcrypt from 'bcrypt';
import { NextResponse } from 'next/server';

import { PrismaClient } from '@prisma/client';

import { findUserByEmail, readUserCsv, User } from '../functions/csvReadWrite';

const usingPrisma = false;
let prisma: PrismaClient;
if (usingPrisma) prisma = new PrismaClient();

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

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

		let foundUser;

		if (usingPrisma) {
			foundUser = await prisma.user.findUnique({
				where: {
					email: email, // use the email to uniquely identify the user
				},
			});
		} else {
			foundUser = findUserByEmail(userData, email);
		}

		if (foundUser && (await bcrypt.compare(password, usingPrisma ? foundUser.hashedPassword : foundUser.password))) {
			// todo remove password from returned user
			return NextResponse.json({ message: "Login successful!", user: foundUser }, { status: 200 });
		} else {
			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 });
	} finally {
		if (usingPrisma) await prisma.$disconnect();
	}
}
