import { NextRequest, NextResponse } from 'next/server';
import { getDBConnexion } from '../../utils';
import { compareSync } from 'bcrypt';

type RequestBody = {
	username?: string;
	password?: string;
};

export const POST = async (req: NextRequest) => {
	const { username, password }: RequestBody = await req.json();

	if (!username || !password) {
		return NextResponse.json(
			{
				error: true,
				message: 'Missing username or password field in request body',
			},
			{
				status: 400,
			}
		);
	}

	try {
		const pool = getDBConnexion();

		const { rows } = await pool.query(
			`SELECT * FROM "user" WHERE "username"=$1 LIMIT 1;`,
			[username]
		);

		await pool.end();

		if (rows.length != 1) {
			return NextResponse.json({
				error: true,
				message: 'User not found',
			});
		}

		const { id, password: hashedPassword } = rows[0];

		if (!compareSync(password, hashedPassword)) {
			return NextResponse.json(
				{
					error: true,
					message: 'Wrong password',
				},
				{
					status: 403,
				}
			);
		}

		return NextResponse.json({
			token: id,
		});
	} catch (error) {
		console.error(error);
		return NextResponse.json(
			{
				error: true,
				message: 'Internal error',
			},
			{
				status: 500,
			}
		);
	}
};
