import { expressionBuilder } from "kysely";
import type Database from "~/schemas/Database";
import { jsonArrayFrom, jsonObjectFrom } from "kysely/helpers/postgres";
import type { UsersId } from "~/schemas/public/Users";
export function getMessagesArray() {
  const eb = expressionBuilder<Database, "chats">();
  return jsonArrayFrom(
    eb
      .selectFrom("messages")
      .selectAll("messages")
      .whereRef("messages.chatid", "=", "chats.chatid")
      .leftJoin("users", "users.id", "messages.sender")
      .select(["users.nome as sender_nome", "users.isAdmin as sender_isAdmin"])
      .orderBy("messages.time", "asc"),
  ).as("messagesArray");
}
export type UserInfoQueryType = {
  id: UsersId;
  username: string;
  email: string;
  nome: string | null;
};

export function getUserInfo() {
  const eb = expressionBuilder<Database, "chats">();
  return jsonObjectFrom(
    eb
      .selectFrom("users")
      .select(["id", "username", "email", "nome"])
      .whereRef("users.id", "=", "chats.user_ref"),
  ).as("userinfo");
}
