import { MeDto } from "@/shared/dto/user/meDto";
interface Permission {
  id: string;
  key: string;
}

interface Position {
  id: string;
  permissions: Permission[];
}

interface EmployeeData {
  id: string;
  positions: Position[];
}

export const useUserDetail = (userDetails?: MeDto) => {
  // Extract permissions from top-level permissions array
  const topLevelPermissions = userDetails?.permissions?.map((permission: Permission) => permission.key) ?? [];
  
  // Extract all unique permission keys from all positions
  const positionPermissions =
    userDetails?.employee?.flatMap((employee: EmployeeData) =>
      employee.positions.flatMap((position: Position) =>
        position.permissions.map((permission: Permission) => permission.key)
      )
    ) ?? [];

  // Combine both top-level and position permissions, removing duplicates
  const permissionKeys = [...new Set([...topLevelPermissions, ...positionPermissions])];

  const checkHaveParent =
    userDetails?.employee?.[0]?.positions?.[0]?.parentPositionId;
  const isLoading = !userDetails;
  const isRO = permissionKeys.includes("can:dispatchRecords");
  const isUnitAdmin = permissionKeys.includes("can:dispatchRecords");

  return {
    // unitId,
    userDetails,
    permissionKeys,
    checkHaveParent,
    isLoading,
    isRO,
    isUnitAdmin,
    error: false,
    hasPermission: (permissionKey: string) =>
      permissionKeys.includes(permissionKey),
  };
};
