import { TRPCError } from "@trpc/server";
import type { ChatsChatid } from "~/schemas/public/Chats";
import type { UsersId } from "~/schemas/public/Users";
import type { Querier } from "~/server/db";

export type ChatUserInfo = {
	id: UsersId;
	username: string;
	email: string;
};

export const getRaw = async ({
	db,
	chatId,
}: {
	db: Querier;
	chatId: ChatsChatid;
}) => {
	try {
		return db
			.selectFrom("chats")
			.selectAll()
			.where("chats.chatid", "=", chatId)
			.executeTakeFirstOrThrow(
				() => new Error(`Chat not found - chatId: ${chatId}`),
			);
	} catch (e) {
		throw new TRPCError({
			code: "BAD_REQUEST",
			message: `Error while getting chat: ${(e as Error).message}`,
		});
	}
};

export const add = async ({ db, userId }: { db: Querier; userId: UsersId }) => {
	try {
		const newChat = await db
			.insertInto("chats")
			.values({
				created_at: new Date(),
				user_ref: userId,
			})
			.returningAll()
			.executeTakeFirstOrThrow(
				() => new Error(`Error while creating chat for userId: ${userId}`),
			);
		return newChat;
	} catch (e) {
		throw new TRPCError({
			code: "BAD_REQUEST",
			message: `Error while creating chat: ${(e as Error).message}`,
		});
	}
};
