import { instanceUserRoles, organizationMemberships, principalPermissionGrants, } from "@rudderhq/db";
import { and, eq, inArray, sql } from "drizzle-orm";
export function accessService(db) {
    async function isInstanceAdmin(userId) {
        if (!userId)
            return false;
        const row = await db
            .select({ id: instanceUserRoles.id })
            .from(instanceUserRoles)
            .where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
            .then((rows) => rows[0] ?? null);
        return Boolean(row);
    }
    async function getMembership(orgId, principalType, principalId) {
        return db
            .select()
            .from(organizationMemberships)
            .where(and(eq(organizationMemberships.orgId, orgId), eq(organizationMemberships.principalType, principalType), eq(organizationMemberships.principalId, principalId)))
            .then((rows) => rows[0] ?? null);
    }
    async function hasPermission(orgId, principalType, principalId, permissionKey) {
        const membership = await getMembership(orgId, principalType, principalId);
        if (!membership || membership.status !== "active")
            return false;
        const grant = await db
            .select({ id: principalPermissionGrants.id })
            .from(principalPermissionGrants)
            .where(and(eq(principalPermissionGrants.orgId, orgId), eq(principalPermissionGrants.principalType, principalType), eq(principalPermissionGrants.principalId, principalId), eq(principalPermissionGrants.permissionKey, permissionKey)))
            .then((rows) => rows[0] ?? null);
        return Boolean(grant);
    }
    async function canUser(orgId, userId, permissionKey) {
        if (!userId)
            return false;
        if (await isInstanceAdmin(userId))
            return true;
        return hasPermission(orgId, "user", userId, permissionKey);
    }
    async function listMembers(orgId) {
        return db
            .select()
            .from(organizationMemberships)
            .where(eq(organizationMemberships.orgId, orgId))
            .orderBy(sql `${organizationMemberships.createdAt} desc`);
    }
    async function listActiveUserMemberships(orgId) {
        return db
            .select()
            .from(organizationMemberships)
            .where(and(eq(organizationMemberships.orgId, orgId), eq(organizationMemberships.principalType, "user"), eq(organizationMemberships.status, "active")))
            .orderBy(sql `${organizationMemberships.createdAt} asc`);
    }
    async function setMemberPermissions(orgId, memberId, grants, grantedByUserId) {
        const member = await db
            .select()
            .from(organizationMemberships)
            .where(and(eq(organizationMemberships.orgId, orgId), eq(organizationMemberships.id, memberId)))
            .then((rows) => rows[0] ?? null);
        if (!member)
            return null;
        await db.transaction(async (tx) => {
            await tx
                .delete(principalPermissionGrants)
                .where(and(eq(principalPermissionGrants.orgId, orgId), eq(principalPermissionGrants.principalType, member.principalType), eq(principalPermissionGrants.principalId, member.principalId)));
            if (grants.length > 0) {
                await tx.insert(principalPermissionGrants).values(grants.map((grant) => ({
                    orgId,
                    principalType: member.principalType,
                    principalId: member.principalId,
                    permissionKey: grant.permissionKey,
                    scope: grant.scope ?? null,
                    grantedByUserId,
                    createdAt: new Date(),
                    updatedAt: new Date(),
                })));
            }
        });
        return member;
    }
    async function promoteInstanceAdmin(userId) {
        const existing = await db
            .select()
            .from(instanceUserRoles)
            .where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
            .then((rows) => rows[0] ?? null);
        if (existing)
            return existing;
        return db
            .insert(instanceUserRoles)
            .values({
            userId,
            role: "instance_admin",
        })
            .returning()
            .then((rows) => rows[0]);
    }
    async function demoteInstanceAdmin(userId) {
        return db
            .delete(instanceUserRoles)
            .where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
            .returning()
            .then((rows) => rows[0] ?? null);
    }
    async function listUserCompanyAccess(userId) {
        return db
            .select()
            .from(organizationMemberships)
            .where(and(eq(organizationMemberships.principalType, "user"), eq(organizationMemberships.principalId, userId)))
            .orderBy(sql `${organizationMemberships.createdAt} desc`);
    }
    async function setUserCompanyAccess(userId, orgIds) {
        const existing = await listUserCompanyAccess(userId);
        const existingByCompany = new Map(existing.map((row) => [row.orgId, row]));
        const target = new Set(orgIds);
        await db.transaction(async (tx) => {
            const toDelete = existing.filter((row) => !target.has(row.orgId)).map((row) => row.id);
            if (toDelete.length > 0) {
                await tx.delete(organizationMemberships).where(inArray(organizationMemberships.id, toDelete));
            }
            for (const orgId of target) {
                if (existingByCompany.has(orgId))
                    continue;
                await tx.insert(organizationMemberships).values({
                    orgId,
                    principalType: "user",
                    principalId: userId,
                    status: "active",
                    membershipRole: "member",
                });
            }
        });
        return listUserCompanyAccess(userId);
    }
    async function ensureMembership(orgId, principalType, principalId, membershipRole = "member", status = "active") {
        const existing = await getMembership(orgId, principalType, principalId);
        if (existing) {
            if (existing.status !== status || existing.membershipRole !== membershipRole) {
                const updated = await db
                    .update(organizationMemberships)
                    .set({ status, membershipRole, updatedAt: new Date() })
                    .where(eq(organizationMemberships.id, existing.id))
                    .returning()
                    .then((rows) => rows[0] ?? null);
                return updated ?? existing;
            }
            return existing;
        }
        return db
            .insert(organizationMemberships)
            .values({
            orgId,
            principalType,
            principalId,
            status,
            membershipRole,
        })
            .returning()
            .then((rows) => rows[0]);
    }
    async function setPrincipalGrants(orgId, principalType, principalId, grants, grantedByUserId) {
        await db.transaction(async (tx) => {
            await tx
                .delete(principalPermissionGrants)
                .where(and(eq(principalPermissionGrants.orgId, orgId), eq(principalPermissionGrants.principalType, principalType), eq(principalPermissionGrants.principalId, principalId)));
            if (grants.length === 0)
                return;
            await tx.insert(principalPermissionGrants).values(grants.map((grant) => ({
                orgId,
                principalType,
                principalId,
                permissionKey: grant.permissionKey,
                scope: grant.scope ?? null,
                grantedByUserId,
                createdAt: new Date(),
                updatedAt: new Date(),
            })));
        });
    }
    async function copyActiveUserMemberships(sourceCompanyId, targetCompanyId) {
        const sourceMemberships = await listActiveUserMemberships(sourceCompanyId);
        for (const membership of sourceMemberships) {
            await ensureMembership(targetCompanyId, "user", membership.principalId, membership.membershipRole, "active");
        }
        return sourceMemberships;
    }
    async function listPrincipalGrants(orgId, principalType, principalId) {
        return db
            .select()
            .from(principalPermissionGrants)
            .where(and(eq(principalPermissionGrants.orgId, orgId), eq(principalPermissionGrants.principalType, principalType), eq(principalPermissionGrants.principalId, principalId)))
            .orderBy(principalPermissionGrants.permissionKey);
    }
    async function setPrincipalPermission(orgId, principalType, principalId, permissionKey, enabled, grantedByUserId, scope = null) {
        if (!enabled) {
            await db
                .delete(principalPermissionGrants)
                .where(and(eq(principalPermissionGrants.orgId, orgId), eq(principalPermissionGrants.principalType, principalType), eq(principalPermissionGrants.principalId, principalId), eq(principalPermissionGrants.permissionKey, permissionKey)));
            return;
        }
        await ensureMembership(orgId, principalType, principalId, "member", "active");
        const existing = await db
            .select()
            .from(principalPermissionGrants)
            .where(and(eq(principalPermissionGrants.orgId, orgId), eq(principalPermissionGrants.principalType, principalType), eq(principalPermissionGrants.principalId, principalId), eq(principalPermissionGrants.permissionKey, permissionKey)))
            .then((rows) => rows[0] ?? null);
        if (existing) {
            await db
                .update(principalPermissionGrants)
                .set({
                scope,
                grantedByUserId,
                updatedAt: new Date(),
            })
                .where(eq(principalPermissionGrants.id, existing.id));
            return;
        }
        await db.insert(principalPermissionGrants).values({
            orgId,
            principalType,
            principalId,
            permissionKey,
            scope,
            grantedByUserId,
            createdAt: new Date(),
            updatedAt: new Date(),
        });
    }
    return {
        isInstanceAdmin,
        canUser,
        hasPermission,
        getMembership,
        ensureMembership,
        listMembers,
        listActiveUserMemberships,
        copyActiveUserMemberships,
        setMemberPermissions,
        promoteInstanceAdmin,
        demoteInstanceAdmin,
        listUserCompanyAccess,
        setUserCompanyAccess,
        setPrincipalGrants,
        listPrincipalGrants,
        setPrincipalPermission,
    };
}
//# sourceMappingURL=access.js.map