import { userProfile } from "../../db/runtime/runtime-schema.js";
import { generateId } from "../../utils/conversations.js";
import "../../utils/index.js";
import { eq } from "drizzle-orm";

//#region src/data-access/runtime/userProfiles.ts
const getUserProfile = (db) => async (userId) => {
	return (await db.select().from(userProfile).where(eq(userProfile.userId, userId)).limit(1))[0] ?? null;
};
const createUserProfileIfNotExists = (db) => async (userId) => {
	const id = generateId();
	const now = (/* @__PURE__ */ new Date()).toISOString();
	await db.insert(userProfile).values({
		id,
		userId,
		timezone: null,
		attributes: {},
		createdAt: now,
		updatedAt: now
	}).onConflictDoNothing();
};
const upsertUserProfile = (db) => async (userId, data) => {
	const id = generateId();
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const result = await db.insert(userProfile).values({
		id,
		userId,
		timezone: data.timezone ?? null,
		attributes: data.attributes ?? {},
		createdAt: now,
		updatedAt: now
	}).onConflictDoUpdate({
		target: userProfile.userId,
		set: {
			...data.timezone !== void 0 && { timezone: data.timezone },
			...data.attributes !== void 0 && { attributes: data.attributes },
			updatedAt: now
		}
	}).returning();
	if (!result[0]) throw new Error(`Failed to upsert user profile for userId: ${userId}`);
	return result[0];
};

//#endregion
export { createUserProfileIfNotExists, getUserProfile, upsertUserProfile };