import { account, invitation, member, organization, ssoProvider } from "../../auth/auth-schema.js";
import { and, eq } from "drizzle-orm";

//#region src/data-access/runtime/auth.ts
const getInitialOrganization = (db) => async (userId) => {
	const [membership] = await db.select({ organizationId: member.organizationId }).from(member).where(eq(member.userId, userId)).orderBy(member.createdAt).limit(1);
	return membership ? { id: membership.organizationId } : null;
};
const queryHasCredentialAccount = (db) => async (userId) => {
	const [row] = await db.select({ id: account.id }).from(account).where(and(eq(account.userId, userId), eq(account.providerId, "credential"))).limit(1);
	return !!row;
};
const querySsoProviderIssuers = (db) => async () => {
	return db.select({ issuer: ssoProvider.issuer }).from(ssoProvider);
};
const querySsoProviderById = (db) => async (providerId) => {
	const [row] = await db.select({ issuer: ssoProvider.issuer }).from(ssoProvider).where(eq(ssoProvider.providerId, providerId)).limit(1);
	return row;
};
const querySsoProviderIds = (db) => async () => {
	return (await db.select({ providerId: ssoProvider.providerId }).from(ssoProvider)).map((r) => r.providerId);
};
const queryOrgAllowedAuthMethods = (db) => async (orgId) => {
	const [org] = await db.select({ allowedAuthMethods: organization.allowedAuthMethods }).from(organization).where(eq(organization.id, orgId)).limit(1);
	return org;
};
const queryMemberExists = (db) => async (userId, organizationId) => {
	const [row] = await db.select({ id: member.id }).from(member).where(and(eq(member.userId, userId), eq(member.organizationId, organizationId))).limit(1);
	return !!row;
};
const queryPendingInvitationExists = (db) => async (email, organizationId) => {
	const [row] = await db.select({ id: invitation.id }).from(invitation).where(and(eq(invitation.email, email), eq(invitation.organizationId, organizationId), eq(invitation.status, "pending"))).limit(1);
	return !!row;
};

//#endregion
export { getInitialOrganization, queryHasCredentialAccount, queryMemberExists, queryOrgAllowedAuthMethods, queryPendingInvitationExists, querySsoProviderById, querySsoProviderIds, querySsoProviderIssuers };