import type { ClientMembershipRole, ClientMembershipStatus, LauncherGlobalRole } from "../../entities/user/types";

export interface LauncherPermissions {
  canOpenAdmin: boolean;
  canManageClients: boolean;
  canManageOwnClient: boolean;
  canManageServiceCatalog: boolean;
  canInviteUsers: boolean;
  canManageAccess: boolean;
  canViewSync: boolean;
}

export function resolveLauncherRole(input: {
  isRoot?: boolean;
  membershipRole?: ClientMembershipRole;
}): LauncherGlobalRole {
  if (input.isRoot) return "root_admin";
  return input.membershipRole ?? "member";
}

export function resolvePermissions(input: {
  launcherRole: LauncherGlobalRole;
  membershipStatus?: ClientMembershipStatus;
}): LauncherPermissions {
  const active = input.membershipStatus !== "disabled";
  const isRoot = input.launcherRole === "root_admin";
  const isSupport = input.launcherRole === "support_admin";
  const isClientAdmin = input.launcherRole === "client_owner" || input.launcherRole === "client_admin";

  return {
    canOpenAdmin: active && (isRoot || isSupport || isClientAdmin),
    canManageClients: active && isRoot,
    canManageOwnClient: active && (isRoot || isClientAdmin),
    canManageServiceCatalog: active && isRoot,
    canInviteUsers: active && (isRoot || isClientAdmin),
    canManageAccess: active && (isRoot || isClientAdmin),
    canViewSync: active && (isRoot || isSupport || isClientAdmin),
  };
}

export function isClientAdminRole(role: LauncherGlobalRole): boolean {
  return role === "client_owner" || role === "client_admin";
}
