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

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

import {
    findUserByEmail, passwordStrengthCheck, readUserCsv, User, writeUserCsv
} 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
		let { email, password, name } = body;
		const accessLevel = "basic";

		const userData = await readUserCsv();

		console.log(userData);
		console.log("Name:", name); // ! remove
		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) {
			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 {
				const passwordHash = await bcrypt.hash(password, 10);
				if (usingPrisma) {
					// todo add sending back newUser
					const newUser = await prisma.user.create({
						data: {
							name,
							email,
							passwordHash,
						},
					});
				} else {
					userData.push({ name, email, password: passwordHash, 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 });
	}
}
