import { TRPCError } from "@trpc/server";
import type { Flags, FlagsId } from "~/schemas/public/Flags";
import type { Querier } from "~/server/db";

export const EditFlagHandler = async ({
	db,
	input,
}: {
	db: Querier;
	input: Flags;
}) => {
	try {
		return await db
			.updateTable("flags")
			.set({
				value: input.value,
			})
			.where("id", "=", input.id)
			.returningAll()
			.execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Error editing flag: ${(e as Error).message}`,
		});
	}
};
export const GetFlagHandler = async ({ db }: { db: Querier }) => {
	try {
		return await db.selectFrom("flags").selectAll().execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Error getting flags: ${(e as Error).message}`,
		});
	}
};

export const GetFlagValueHandler = async ({
	db,
	id,
}: {
	db: Querier;
	id: string;
}) => {
	try {
		const flag = await db
			.selectFrom("flags")
			.select("value")
			.where("id", "=", id as FlagsId)
			.executeTakeFirst();
		return flag?.value ?? null;
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Error getting flag value: ${(e as Error).message}`,
		});
	}
};

export const RemoveFlagHandler = async ({
	db,
	id,
}: {
	db: Querier;
	id: FlagsId;
}) => {
	try {
		await db.deleteFrom("flags").where("id", "=", id).execute();
		return true;
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Error removing flag: ${(e as Error).message}`,
		});
	}
};
export const AddFlagHandler = async ({
	db,
	input,
}: {
	db: Querier;
	input: Flags;
}) => {
	try {
		await db
			.insertInto("flags")
			.values({
				id: input.id,
				value: input.value,
			})
			.onConflict((oc) => oc.column("id").doNothing())
			.returningAll()
			.execute();
		return true;
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Error adding flag: ${(e as Error).message}`,
		});
	}
};
