import { isValid } from "date-fns";
import { expressionBuilder } from "kysely";
import { jsonArrayFrom, jsonObjectFrom } from "kysely/helpers/postgres";
import type Database from "~/schemas/Database";
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");
}

export function withImages() {
	const eb = expressionBuilder<Database, "annunci">();
	return jsonArrayFrom(
		eb
			.selectFrom("images_refs")
			.select(["img", "thumb"])
			.whereRef("images_refs.codice", "=", "annunci.codice")
			.orderBy("images_refs.ordine", "asc"),
	).as("images");
}

export function withVideos() {
	const eb = expressionBuilder<Database, "annunci">();
	return jsonArrayFrom(
		eb
			.selectFrom("videos_refs")
			.select(["video", "thumb"])
			.whereRef("videos_refs.codice", "=", "annunci.codice")
			.orderBy("videos_refs.ordine", "asc"),
	).as("videos");
}

export function parseNullableDateString(str: string | null): Date | null {
	if (str === null) {
		return null;
	}
	const date = new Date(str);
	return isValid(date) ? date : null;
}
