import type { RequestHandler } from '@sveltejs/kit';
import { Report, User } from '$lib/server/database';
import * as crypto from 'crypto';
import { env } from '$env/dynamic/private';

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

	const data: { reporter: string; reported: string; reason: string } = await request.json();

	if (data.reporter == null || data.reported == null || data.reason == null)
		return new Response(null, { status: 400 });

	const reporter = await User.findOne({ where: { uuid: data.reporter } });
	const reported = await User.findOne({ where: { uuid: data.reported } });

	if (reporter == null || reported == null) return new Response(null, { status: 400 });

	const report = await Report.create({
		subject: data.reason,
		body: null,
		draft: true,
		status: 'none',
		url_hash: crypto.randomBytes(18).toString('hex'),
		completed: false,
		reporter_id: reporter.id,
		reported_id: reported.id
	});

	return new Response(
		JSON.stringify({
			url: `${url.protocol}//${url.host}${env.PUBLIC_BASE_PATH || ''}/report/${report.url_hash}`
		}),
		{
			status: 201
		}
	);
}) satisfies RequestHandler;
