import { useQuery } from '@tanstack/react-query';
import { useInject } from '@/lib/di/hooks/useInject';
import { DRIVER_SERVICE_TOKEN } from '@/lib/di/tokens';
import { enhanceQueryResult } from '@/lib/di/hooks/useReactQueryWithApiError';

type TeamMemberRole = 'owner' | 'manager' | 'member';

interface TeamRosterMember {
  driver: unknown;
  role: TeamMemberRole;
  joinedAt: string;
  rating: number | null;
  overallRank: number | null;
}

export function useTeamRoster(memberships: Array<{
  driverId: string;
  role: string;
  joinedAt: string;
}>) {
  const driverService = useInject(DRIVER_SERVICE_TOKEN);

  const queryResult = useQuery<TeamRosterMember[]>({
    queryKey: ['teamRoster', memberships],
    queryFn: async () => {
      // Get driver details for each membership
      const membersWithDetails = await Promise.all(
        memberships.map(async (m) => {
          const driver = await driverService.findById(m.driverId);
          // Convert role to TeamMemberRole
          const role: TeamMemberRole = m.role === 'owner' ? 'owner' : 
                                      m.role === 'manager' ? 'manager' : 'member';
          return {
            driver: driver || { id: m.driverId, name: 'Unknown Driver', country: 'Unknown', position: 'N/A', races: '0', impressions: '0', team: 'None' },
            role,
            joinedAt: m.joinedAt,
            rating: null, // DriverDTO doesn't include rating
            overallRank: null, // DriverDTO doesn't include overallRank
          };
        })
      );
      return membersWithDetails;
    },
    enabled: memberships.length > 0,
  });

  return enhanceQueryResult(queryResult);
}