import type { Map as MapLibreMap } from "maplibre-gl";

export const SUPPLY_ASSET_IMAGE_IDS = {
  valve: "supply-valve",
  reservoir: "supply-reservoir",
  pump: "supply-pump",
  tank: "supply-tank"
} as const;

export const SUPPLY_ASSET_ICON_PATHS = {
  valve: "/map/valve.png",
  reservoir: "/map/reservoir.png",
  pump: "/map/pump.png",
  tank: "/map/tank.png"
} as const;

export const SUPPLY_ASSET_MAP_ICON_PATHS = SUPPLY_ASSET_ICON_PATHS;

export type SupplyAssetImageRegistrationResult = {
  status: "ready" | "degraded";
  failedImageIds: string[];
};

const ACTIVE_SUPPLY_ASSET_ICON_KEYS = ["valve", "reservoir", "pump", "tank"] as const;

export async function registerSupplyAssetImages(
  map: Pick<MapLibreMap, "loadImage" | "addImage" | "hasImage">
): Promise<SupplyAssetImageRegistrationResult> {
  const failedImageIds: string[] = [];

  for (const key of ACTIVE_SUPPLY_ASSET_ICON_KEYS) {
    const imageId = SUPPLY_ASSET_IMAGE_IDS[key];
    if (map.hasImage(imageId)) continue;

    try {
      const image = await loadImage(map, SUPPLY_ASSET_MAP_ICON_PATHS[key]);
      addImageIfMissing(map, imageId, image);
    } catch {
      failedImageIds.push(imageId);
    }
  }

  return {
    status: failedImageIds.length > 0 ? "degraded" : "ready",
    failedImageIds
  };
}

async function loadImage(map: Pick<MapLibreMap, "loadImage">, path: string) {
  const response = await map.loadImage(path);
  return response.data;
}

function addImageIfMissing(
  map: Pick<MapLibreMap, "addImage" | "hasImage">,
  imageId: string,
  image: Awaited<ReturnType<typeof loadImage>>
) {
  if (!map.hasImage(imageId)) map.addImage(imageId, image, { pixelRatio: 2 });
}
