import {
  DEFAULT_ADMIN_PERMISSIONS,
  DEFAULT_MEMBER_PERMISSIONS,
  DEFAULT_OWNER_PERMISSIONS,
  type Permission
} from './permissions';

export type SystemRole = 'standard' | 'super_admin';
export type MembershipRole = 'owner' | 'admin' | 'member';
export type OrganizationRole = 'admin' | 'user';
export type BusinessRole = 'IT' | 'HRD' | 'EMPLOYEE';

type RoleContext = {
  businessRole?: BusinessRole | null;
  systemRole?: string | null;
  membershipRole?: string | null;
  role?: string | null;
};

export function isSuperAdmin(systemRole?: string | null): systemRole is 'super_admin' {
  return systemRole === 'super_admin';
}

export function isOrganizationAdminRole(role?: string | null) {
  return role === 'owner' || role === 'admin';
}

export function normalizeOrganizationRole(role?: string | null): OrganizationRole | null {
  if (!role) {
    return null;
  }

  return isOrganizationAdminRole(role) ? 'admin' : 'user';
}

export function getBusinessRole({
  businessRole,
  systemRole,
  membershipRole,
  role
}: RoleContext): BusinessRole | null {
  if (businessRole) {
    return businessRole;
  }

  if (isSuperAdmin(systemRole)) {
    return 'IT';
  }

  if (membershipRole) {
    return isOrganizationAdminRole(membershipRole) ? 'HRD' : 'EMPLOYEE';
  }

  if (role) {
    return role === 'admin' ? 'HRD' : 'EMPLOYEE';
  }

  return null;
}

export function isHRD(context: RoleContext) {
  return getBusinessRole(context) === 'HRD' || isSuperAdmin(context.systemRole);
}

export function hasBusinessRoleAccess(requiredRole: BusinessRole, context: RoleContext) {
  if (requiredRole === 'HRD') {
    return isHRD(context);
  }

  return getBusinessRole(context) === requiredRole;
}

export function isIT(context: RoleContext) {
  return getBusinessRole(context) === 'IT';
}

export function isEmployee(context: RoleContext) {
  return getBusinessRole(context) === 'EMPLOYEE';
}

export function canAccessEmployeeArea(context: RoleContext) {
  return getBusinessRole(context) !== null;
}

export function getDefaultPermissionsForRole(
  role: OrganizationRole | MembershipRole
): Permission[] {
  if (role === 'owner') {
    return [...DEFAULT_OWNER_PERMISSIONS];
  }

  if (role === 'admin' || role === 'user') {
    return role === 'admin'
      ? [...DEFAULT_ADMIN_PERMISSIONS]
      : [...DEFAULT_MEMBER_PERMISSIONS];
  }

  return isOrganizationAdminRole(role)
    ? [...DEFAULT_ADMIN_PERMISSIONS]
    : [...DEFAULT_MEMBER_PERMISSIONS];
}

export function canManageUsers({
  businessRole,
  systemRole,
  membershipRole,
  role
}: {
  businessRole?: BusinessRole | null;
  systemRole?: string | null;
  membershipRole?: string | null;
  role?: string | null;
}) {
  return isIT({
    businessRole,
    systemRole,
    membershipRole,
    role
  });
}

export function canCreateOrganizer(systemRole?: string | null) {
  return isSuperAdmin(systemRole);
}

export function canAssignAdminRole(systemRole?: string | null) {
  return isSuperAdmin(systemRole);
}
