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

export const GET = async (req: NextRequest) => {
	const userID = req.headers.get('Authorization');

	if (!userID) {
		return NextResponse.json(
			{
				error: true,
				message: 'Unauthorized request',
			},
			{
				status: 403,
			}
		);
	}

	try {
		const pool = getDBConnexion();

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

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

		await pool.end();

		return NextResponse.json(rows[0]);
	} catch (error) {
		console.error(error);
		return NextResponse.json(
			{
				error: true,
				message: 'Internal error',
			},
			{
				status: 500,
			}
		);
	}
};

type RequestBody = {
	type?: 'username' | 'password';
	username?: string;
	currentPassword?: string;
	newPassword?: string;
};

export const PUT = async (req: NextRequest) => {
	const userID = req.headers.get('Authorization');

	const { type, username, currentPassword, newPassword }: RequestBody =
		await req.json();

	if (!userID) {
		return NextResponse.json(
			{
				error: true,
				message: 'Unauthorized request',
			},
			{
				status: 403,
			}
		);
	}

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

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

		try {
			const pool = getDBConnexion();

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

			if (rowCount > 0) {
				return NextResponse.json(
					{
						error: true,
						message: 'Username already used',
					},
					{
						status: 409,
					}
				);
			}

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

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

			await pool.query(`UPDATE "user" SET "username"=$1 WHERE "id"=$2;`, [
				username,
				userID,
			]);

			await pool.end();

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

	if (type == 'password') {
		if (!currentPassword || !newPassword) {
			return NextResponse.json(
				{
					error: true,
					message:
						'Missing currentPassword and/or newPassword field(s) in request body',
				},
				{
					status: 400,
				}
			);
		}

		try {
			const pool = getDBConnexion();

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

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

			const { password: currentHashedPassword } = rows[0];

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

			const newHashedPassword = hashSync(newPassword, 10);

			await pool.query(`UPDATE "user" SET "password"=$1 WHERE "id"=$2`, [
				newHashedPassword,
				userID,
			]);

			await pool.end();

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

export const DELETE = async (req: NextRequest) => {
	const userID = req.headers.get('Authorization');

	try {
		const pool = getDBConnexion();

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

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

		await pool.query(`DELETE FROM "user" WHERE "id"=$1 LIMIT 1;`, [userID]);

		await pool.end();

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