import type { RequestHandler } from '@sveltejs/kit';
import { Report, sequelize, StrikePunishment, StrikeReason, User } from '$lib/server/database';
import { env } from '$env/dynamic/private';
import { Op } from 'sequelize';

export const GET = (async ({ url }) => {
	if (env.REPORT_SECRET && url.searchParams.get('secret') !== env.REPORT_SECRET)
		return new Response(null, { status: 401 });

	const uuid = url.searchParams.get('uuid');
	if (uuid == null) return new Response(null, { status: 400 });

	const user = await User.findOne({ where: { uuid: uuid } });
	if (user == null) return new Response(null, { status: 404 });

	const query = (await Report.findOne({
		where: { reported_id: user.id },
		attributes: [
			[sequelize.fn('SUM', sequelize.col('strike_reason.weight')), 'weight'],
			[sequelize.fn('MAX', sequelize.col('striked_at')), 'striked_at']
		],
		include: { model: StrikeReason, as: 'strike_reason' }
	})) as { dataValues: { weight: number | null; striked_at: Date | null } } | null;
	const ban_time = (
		await StrikePunishment.findOne({
			attributes: ['punishment_in_seconds'],
			where: { type: ['ban'], weight: { [Op.lte]: query?.dataValues.weight } },
			order: [['weight', 'DESC']]
		})
	)?.punishment_in_seconds;
	const outlawed_time = (
		await StrikePunishment.findOne({
			attributes: ['punishment_in_seconds'],
			where: { type: ['outlawed'], weight: { [Op.lte]: query?.dataValues.weight } },
			order: [['weight', 'DESC']]
		})
	)?.punishment_in_seconds;

	return new Response(
		JSON.stringify({
			uuid: user.uuid,
			username: user.username,
			firstname: user.firstname,
			lastname: user.lastname,
			banned_until:
				query && query.dataValues.striked_at && ban_time
					? Math.round(query.dataValues.striked_at.getTime() / 1000 + ban_time)
					: null,
			outlawed_until:
				query && query.dataValues.striked_at && outlawed_time
					? Math.round(query.dataValues.striked_at.getTime() / 1000 + outlawed_time)
					: null
		}),
		{ status: 200 }
	);
}) satisfies RequestHandler;
