import "server-only"

import { cache } from "react"
import { and, eq, inArray } from "drizzle-orm"

import { db } from "@/shared/db"
import { rolePermissions, roles } from "@/shared/db/schema"
import { isPermission } from "@/shared/lib/type-guards"
import { getAllPermissionMetas } from "./lib/permission-catalog"

/**
 * Count how many enabled roles have each permission.
 *
 * Returns a map of permission value → role count. Only permissions that
 * appear in the permission catalog are included; only enabled roles are
 * counted (disabled roles do not contribute permissions at login time).
 */
export const getPermissionRoleCounts = cache(async (): Promise<Record<string, number>> => {
  const allPermissionValues = getAllPermissionMetas().map((m) => m.value)
  if (allPermissionValues.length === 0) return {}

  const rows = await db
    .select({ permission: rolePermissions.permission })
    .from(rolePermissions)
    .innerJoin(roles, eq(rolePermissions.roleId, roles.id))
    .where(and(eq(roles.isEnabled, true), inArray(rolePermissions.permission, allPermissionValues)))

  const counts: Record<string, number> = {}
  for (const row of rows) {
    const perm = isPermission(row.permission) ? row.permission : null
    if (perm) {
      counts[perm] = (counts[perm] ?? 0) + 1
    }
  }
  return counts
})
