import { useQuery } from '@tanstack/react-query';

import { $api } from '@/api/api';
import { ICompany } from '@/types/ICompnay';
import { IVehicle } from '@/types/IVehicle';

export const useVehicleGPS = (id: string) => {
  const query = useQuery({
    queryKey: ['vehicle', id],
    queryFn: () => {
      return $api
        .get(`/StandardApiAction_getDeviceStatus.action?devIdno=${id}`)
        .then((res) => res.data);
    },
    refetchInterval: 1000,
  });

  return query;
};

export const useVehicleGPSMultiple = (ids: string[]) => {
  const query = useQuery({
    queryKey: ['vehicle', ids],
    queryFn: async () => {
      return Object.fromEntries(
        await Promise.all(
          ids.map((id) =>
            $api
              .get(`/StandardApiAction_getDeviceStatus.action?devIdno=${id}`)
              .then((res) => [res.data.status[0].vid, res.data.status[0]]),
          ),
        ),
      );
    },
    refetchInterval: 1000,
  });

  return query;
};

export const useVehicleList = () => {
  const query = useQuery({
    queryKey: ['vehicle', 'list'],
    queryFn: () => {
      return $api
        .get<{
          companys: ICompany[];
          result: 0;
          vehicles: IVehicle[];
        }>(`/StandardApiAction_queryUserVehicle.action?jsession`)
        .then((res) => res.data);
    },
  });

  return query;
};

export const useVehicleDeviceStatus = () => {
  const query = useQuery({
    queryKey: ['vehicle', 'status'],
    queryFn: async () => {
      const res = await $api
        .get(`/StandardApiAction_getDeviceOlStatus.action?jsession`)
        .then((res) => res.data);

      return res.onlines;
    }
  });

  return query;
};
