import client from "./client";

// ── Types ────────────────────────────────────────────────────────────

export interface HeatmapMetadata {
  name: string;
  value: string;
}

export interface HeatmapTechnique {
  techniqueID: string;
  tactic: string;
  color: string;
  score: number;
  comment: string;
  enabled: boolean;
  metadata: HeatmapMetadata[];
}

export interface HeatmapLayer {
  name: string;
  versions: {
    attack: string;
    navigator: string;
    layer: string;
  };
  domain: string;
  description: string;
  filters: {
    platforms: string[];
  };
  gradient: {
    colors: string[];
    minValue: number;
    maxValue: number;
  };
  techniques: HeatmapTechnique[];
}

export interface HeatmapFilters {
  platforms?: string;
  tactics?: string;
  min_score?: number;
}

// ── API Functions ────────────────────────────────────────────────────

/** Fetch the coverage heatmap layer. */
export async function getHeatmapCoverage(filters?: HeatmapFilters): Promise<HeatmapLayer> {
  const { data } = await client.get<HeatmapLayer>("/heatmap/coverage", { params: filters });
  return data;
}

/** Fetch the threat actor heatmap layer. */
export async function getHeatmapThreatActor(
  actorId: string,
  filters?: HeatmapFilters,
): Promise<HeatmapLayer> {
  const { data } = await client.get<HeatmapLayer>(`/heatmap/threat-actor/${actorId}`, {
    params: filters,
  });
  return data;
}

/** Fetch the detection rules heatmap layer. */
export async function getHeatmapDetectionRules(filters?: HeatmapFilters): Promise<HeatmapLayer> {
  const { data } = await client.get<HeatmapLayer>("/heatmap/detection-rules", { params: filters });
  return data;
}

/** Fetch the campaign heatmap layer. */
export async function getHeatmapCampaign(
  campaignId: string,
  filters?: HeatmapFilters,
): Promise<HeatmapLayer> {
  const { data } = await client.get<HeatmapLayer>(`/heatmap/campaign/${campaignId}`, {
    params: filters,
  });
  return data;
}

/** Export a heatmap layer as a Navigator JSON file (returns blob URL). */
export async function exportNavigatorJSON(
  layerType: string,
  layerId?: string,
  filters?: HeatmapFilters,
): Promise<Blob> {
  const params: Record<string, string | number | undefined> = {
    layer: layerType,
    layer_id: layerId,
    ...filters,
  };
  const { data } = await client.get("/heatmap/export-navigator", {
    params,
    responseType: "blob",
  });
  return data;
}
