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

export type ChatMessage = Messages & {
	sender_isAdmin: boolean;
	sender_nome: string;
};

export const editMessage = async ({
	db,
	messageId,
	message,
}: {
	db: Querier;
	messageId: MessagesMessageid;
	message: string;
}) => {
	try {
		return await db
			.updateTable("messages")
			.set({
				message: message,
			})
			.where("messages.messageid", "=", messageId)
			.returning("messageid")
			.execute();
	} catch (e) {
		throw new TRPCError({
			code: "BAD_REQUEST",
			message: `Error while editing message: ${(e as Error).message}`,
		});
	}
};

export const setReadMessage = async ({
	db,
	chatId,
	reader,
}: {
	db: Querier;
	chatId: ChatsChatid;
	reader: UsersId;
}) => {
	try {
		await db
			.updateTable("messages")
			.set({
				isread: true,
			})
			.where("messages.isread", "=", false)
			.where("messages.sender", "!=", reader)
			.where("messages.chatid", "=", chatId)
			.returning("messages.chatid")
			.execute();
	} catch (e) {
		throw new TRPCError({
			code: "BAD_REQUEST",
			message: `Error while setting read status: ${(e as Error).message}`,
		});
	}
};
