import { member, organization } from "../../auth/auth-schema.js";
import { orgEntitlement } from "../../db/runtime/runtime-schema.js";
import { and, eq, like, or, sql } from "drizzle-orm";

//#region src/data-access/runtime/entitlements.ts
const listOrgEntitlements = (db) => async (orgId) => {
	return await db.select({
		resourceType: orgEntitlement.resourceType,
		maxValue: orgEntitlement.maxValue
	}).from(orgEntitlement).where(eq(orgEntitlement.organizationId, orgId));
};
async function dalResolveEntitlement(db, orgId, resourceType) {
	const rows = await db.select({ maxValue: orgEntitlement.maxValue }).from(orgEntitlement).where(and(eq(orgEntitlement.organizationId, orgId), eq(orgEntitlement.resourceType, resourceType)));
	if (rows.length === 0) return null;
	return rows[0].maxValue;
}
async function dalSelectEntitlementForUpdate(tx, orgId, resourceType) {
	const rows = await tx.select({ maxValue: orgEntitlement.maxValue }).from(orgEntitlement).where(and(eq(orgEntitlement.organizationId, orgId), eq(orgEntitlement.resourceType, resourceType))).for("update");
	return rows.length === 0 ? null : rows[0].maxValue;
}
async function dalGetServiceAccountUserId(db, orgId) {
	return (await db.select({ serviceAccountUserId: organization.serviceAccountUserId }).from(organization).where(eq(organization.id, orgId)))[0]?.serviceAccountUserId ?? null;
}
async function dalCountMembersByRoleBucket(db, orgId, isAdminBucket, serviceAccountUserId) {
	const memberCondition = isAdminBucket ? or(eq(member.role, "owner"), eq(member.role, "admin")) : eq(member.role, "member");
	const memberWhere = serviceAccountUserId ? and(eq(member.organizationId, orgId), memberCondition, sql`${member.userId} != ${serviceAccountUserId}`) : and(eq(member.organizationId, orgId), memberCondition);
	const [result] = await db.select({ count: sql`count(*)::int` }).from(member).where(memberWhere);
	return result?.count ?? 0;
}
async function dalSumSeatEntitlements(db, orgId) {
	const rows = await db.select({ maxValue: orgEntitlement.maxValue }).from(orgEntitlement).where(and(eq(orgEntitlement.organizationId, orgId), like(orgEntitlement.resourceType, "seat:%")));
	if (rows.length === 0) return null;
	return rows.reduce((sum, r) => sum + r.maxValue, 0);
}

//#endregion
export { dalCountMembersByRoleBucket, dalGetServiceAccountUserId, dalResolveEntitlement, dalSelectEntitlementForUpdate, dalSumSeatEntitlements, listOrgEntitlements };