import { usePageDataMultiple } from '@/lib/page/usePageData';
import { useInject } from '@/lib/di/hooks/useInject';
import { DRIVER_SERVICE_TOKEN, TEAM_SERVICE_TOKEN } from '@/lib/di/tokens';

export function useDriverProfilePageData(driverId: string) {
  const driverService = useInject(DRIVER_SERVICE_TOKEN);
  const teamService = useInject(TEAM_SERVICE_TOKEN);

  return usePageDataMultiple({
    driverProfile: {
      queryKey: ['driverProfile', driverId],
      queryFn: () => driverService.getDriverProfile(driverId),
      enabled: !!driverId,
    },
    teamMemberships: {
      queryKey: ['teamMemberships', driverId],
      queryFn: async () => {
        if (!driverId) return [];
        
        const allTeamsResult = await teamService.getAllTeams();
        if (allTeamsResult.isErr()) return [];
        const allTeams = allTeamsResult.unwrap();

        let teamMemberships: Array<{
          team: { id: string; name: string };
          role: string;
          joinedAt: Date;
        }> = [];
        
        for (const team of allTeams) {
          const teamMembersResult = await teamService.getTeamMembers(team.id, driverId, '');
          if (teamMembersResult.isErr()) continue;
          const teamMembers = teamMembersResult.unwrap();

          const membership = teamMembers?.find(member => member.driverId === driverId);
          if (membership) {
            teamMemberships.push({
              team: {
                id: team.id,
                name: team.name,
              },
              role: membership.role,
              joinedAt: new Date(membership.joinedAt),
            });
          }
        }
        
        return teamMemberships;
      },
      enabled: !!driverId,
    },
  });
}