import { isSuperAdminRole } from "../../../lib/roles";

export const HANMAC_FAMILY_TENANT_ID = "038326b6-954a-48a7-a85f-efd83f62b82a";
export const HANMAC_FAMILY_TENANT_SLUG = "hanmac-family";

export type WorksmobileAccessProfile = {
  role?: string;
  tenantId?: string;
  tenantSlug?: string;
  tenant?: {
    id?: string;
    slug?: string;
    config?: Record<string, unknown>;
  };
  manageableTenants?: Array<{
    id?: string;
    slug?: string;
    config?: Record<string, unknown>;
  }>;
};

export function isWorksmobileExcludedConfig(config?: Record<string, unknown>) {
  const rawValue = config?.worksmobileExcluded;
  return (
    rawValue === true ||
    String(rawValue ?? "")
      .trim()
      .toLowerCase() === "true"
  );
}

function isProfileTenantWorksmobileExcluded(
  profile?: WorksmobileAccessProfile | null,
) {
  if (isWorksmobileExcludedConfig(profile?.tenant?.config)) {
    return true;
  }
  return (profile?.manageableTenants ?? []).some((tenant) => {
    const isCurrentTenant =
      (profile?.tenantId && tenant.id === profile.tenantId) ||
      (profile?.tenantSlug && tenant.slug === profile.tenantSlug);
    return isCurrentTenant && isWorksmobileExcludedConfig(tenant.config);
  });
}

export function canAccessWorksmobile(
  profile?: WorksmobileAccessProfile | null,
) {
  if (isSuperAdminRole(profile?.role)) {
    return true;
  }
  if (isProfileTenantWorksmobileExcluded(profile)) {
    return false;
  }
  return (profile?.manageableTenants ?? []).some(
    (tenant) =>
      !isWorksmobileExcludedConfig(tenant.config) &&
      (tenant.id === HANMAC_FAMILY_TENANT_ID ||
        tenant.slug === HANMAC_FAMILY_TENANT_SLUG),
  );
}
