import { member, user } from "../../auth/auth-schema.js";
import { and, eq } from "drizzle-orm";

//#region src/data-access/runtime/users.ts
/**
* User data access layer
* All database queries for Better Auth's user table
*/
/**
* Get user by ID
*/
const getUserById = (db) => async (userId) => {
	return (await db.select().from(user).where(eq(user.id, userId)).limit(1))[0] || null;
};
/**
* Get user by email
*/
const getUserByEmail = (db) => async (email) => {
	return (await db.select().from(user).where(eq(user.email, email)).limit(1))[0] || null;
};
/**
* Get organization member by email
* Returns the user if they are a member of the specified organization
*/
const getOrganizationMemberByUserId = (db) => async (organizationId, userId) => {
	return (await db.select({
		id: user.id,
		name: user.name,
		email: user.email,
		emailVerified: user.emailVerified,
		image: user.image,
		createdAt: user.createdAt,
		updatedAt: user.updatedAt,
		role: member.role,
		memberId: member.id
	}).from(member).innerJoin(user, eq(member.userId, user.id)).where(and(eq(member.organizationId, organizationId), eq(user.id, userId))).limit(1))[0] || null;
};
const getOrganizationMemberByEmail = (db) => async (organizationId, email) => {
	return (await db.select({
		id: user.id,
		name: user.name,
		email: user.email,
		emailVerified: user.emailVerified,
		image: user.image,
		createdAt: user.createdAt,
		updatedAt: user.updatedAt,
		role: member.role,
		memberId: member.id
	}).from(member).innerJoin(user, eq(member.userId, user.id)).where(and(eq(member.organizationId, organizationId), eq(user.email, email))).limit(1))[0] || null;
};

//#endregion
export { getOrganizationMemberByEmail, getOrganizationMemberByUserId, getUserByEmail, getUserById };