import type { RequestHandler } from "./$types";
import { z } from "zod";
import { UserRoleMap } from "$lib/core/enums";
import { db, eq } from "@pkg/db";
import { user } from "@pkg/db/schema";
import { Logger } from "$lib/core/logger";
import { env } from "$env/dynamic/private";
import { nanoid } from "nanoid";

function isAuthorized(authHeader?: string | null) {
	if (!authHeader) return false;
	const authToken = authHeader.toString().replace("Bearer ", "");
	return authToken === env.DEBUG_API_KEY;
}

export const GET: RequestHandler = async ({ request }) => {
	if (!isAuthorized(request.headers.get("Authorization"))) {
		return new Response("Unauthorized", { status: 401 });
	}
	const users = await db.query.user.findMany({});
	return new Response(JSON.stringify({ users }), { status: 200 });
};

export const PUT: RequestHandler = async ({ request }) => {
	if (!isAuthorized(request.headers.get("Authorization"))) {
		return new Response("Unauthorized", { status: 401 });
	}

	const data = await request.json();

	if (!data.username) {
		return new Response("Invalid data", { status: 400 });
	}

	await db
		.update(user)
		.set({ role: UserRoleMap.ADMIN })
		.where(eq(user.username, data.username))
		.execute();

	return new Response("Not implemented", { status: 200 });
};

export const POST: RequestHandler = async ({ request }) => {
	if (!isAuthorized(request.headers.get("Authorization"))) {
		return new Response("Unauthorized", { status: 401 });
	}
	const data = await request.json();
	const res = z
		.object({
			username: z.string(),
			usertype: z.enum([UserRoleMap.AGENT, UserRoleMap.ADMIN]),
		})
		.safeParse(data);

	if (!res.success) {
		return new Response("Invalid data", { status: 400 });
	}

	if (
		!!(
			await db.query.user
				.findFirst({
					where: eq(user.role, UserRoleMap.AGENT),
					columns: { id: true },
				})
				.execute()
		)?.id
	) {
		return new Response("Admin already exists", { status: 400 });
	}

	Logger.info(`Creating ${res.data.username} (${res.data.usertype})`);

	Logger.debug(env.PUBLIC_URL);

	request.headers.set("Authorization", `Bearer`);

	const out = await db.insert(user).values({
		id: nanoid(),
		username: res.data.username,
		email: `${res.data.username}@${env.PUBLIC_URL}`,
		emailVerified: false,
		name: res.data.username,
		role: res.data.usertype,
		createdAt: new Date(),
		updatedAt: new Date(),
	});

	Logger.debug(out);

	return new Response(JSON.stringify({ ...out }), { status: 200 });
};
