import { NetworkIdsResult } from 'interfaces/networks';
import { LocationsForNetwork } from 'interfaces/locations';
import { Location } from 'interfaces/locations';
import { getQuery } from 'mystique/hooks/getQuery';

const networkIdsQuery = `query ($ref: String!) {
    virtualCatalogue(ref: $ref) {
          networkIds
    }
  }
`;

const locationsForNetworkQuery = `query ($networkIds: [String]) {
  networks(ref: $networkIds) {
    edges {
      node {
        locations (first: 100) {
          edges {
            node {
              name
              ref
              primaryAddress {
                postcode
              }
            }
          }
        }
      }
    }
  }
}
`;

interface GetBaseLocationsProps {
  activeRetailer: string;
}

export const getBaseLocations = async ({
  activeRetailer,
}: GetBaseLocationsProps) => {
  const networkIds: string[] = [];
  await getQuery<NetworkIdsResult>(networkIdsQuery, {
    ref: `VC:BASE:${activeRetailer}`, // TODO virtual catalogue ref (for example, BASE or VC:BASE)
  }).then((resp) => {
    const catalogue = resp.data?.virtualCatalogue;
    if (catalogue) {
      networkIds.push(...catalogue.networkIds);
    }
  });
  const uniqueLocations: Location[] = [];
  await getQuery<LocationsForNetwork>(locationsForNetworkQuery, {
    networkIds,
  }).then((resp) => {
    if (resp.data?.networks) {
      const allLocations: Location[] = resp.data?.networks.edges.flatMap(
        (network) => {
          const allLocations = network.node.locations.edges.map((location) => {
            return {
              ref: location.node.ref,
              name: location.node.name,
              postcode: location.node.primaryAddress.postcode,
            };
          });
          return [...allLocations];
        },
      );

      allLocations.forEach((location) => {
        if (!uniqueLocations.includes(location)) {
          uniqueLocations.push(location);
        }
      });
    }
  });

  return uniqueLocations;
};