import { type FieldNamesMarkedBoolean } from 'react-hook-form';

import { type MeUser, type User, type UserProfile } from 'src/types/user';
import { hasAnyPermissions, ROUTE_PERMISSIONS } from 'src/utils/permissions';

export const canViewAcknowledgements = (permissions: string[]): boolean =>
  hasAnyPermissions(permissions, ROUTE_PERMISSIONS.USER_ACKNOWLEDGEMENTS);

export const findIndexOnPaginatedPages = (
  id: string | number,
  pages: { data: any[] }[],
): [pageIndex: number, itemIndex: number] => {
  for (let i = 0; i < pages.length; i++) {
    const itemIndex = pages[i]?.data?.findIndex(elem => elem.id === id);

    if (itemIndex !== undefined && itemIndex !== -1) {
      return [i, itemIndex];
    }
  }

  return [-1, -1];
};

export const findIndexOnCursorPaginatedPages = (
  id: string | number,
  pages: { data: { items: any[] } }[],
): [pageIndex: number, itemIndex: number] => {
  for (let i = 0; i < pages.length; i++) {
    const itemIndex = pages[i]?.data?.items?.findIndex(elem => elem.id === id);

    if (itemIndex !== undefined && itemIndex !== -1) {
      return [i, itemIndex];
    }
  }

  return [-1, -1];
};

export const canSendMessage = (
  allowCreateChats: boolean,
  canViewChats: boolean,
  user: User | UserProfile,
  loggedUser: MeUser | UserProfile,
) => allowCreateChats && canViewChats && user.id !== loggedUser.id;

export function getDirtyValues<T extends object>(
  dirtyFields: FieldNamesMarkedBoolean<T>,
  allValues: T,
): Partial<T> {
  if (dirtyFields === true || Array.isArray(dirtyFields)) return allValues;
  return Object.fromEntries(
    Object.entries(dirtyFields).map(([key, dirty]) => [
      key,
      getDirtyValues(
        dirty as FieldNamesMarkedBoolean<object>,
        (allValues as Record<string, unknown>)[key] as object,
      ),
    ]),
  ) as Partial<T>;
}
