import {
  DeviceConfigAckEntity,
  DeviceConfigEntity,
  getLatestDeviceConfigAck,
  toDeviceConfigAckPayload,
  toDeviceConfigPayload
} from "../store/deviceConfigStore";
import { listMqttMessages, toMqttMessagePayload } from "../store/mqttMessageStore";

type ConfigDriftStatus = "applied" | "pending_ack" | "failed_ack" | "stale_ack" | "never_pushed";

function deriveConfigDriftStatus(config: DeviceConfigEntity, latestAck: DeviceConfigAckEntity | null): ConfigDriftStatus {
  if (!latestAck) {
    return "pending_ack";
  }

  if (latestAck.config_version < config.config_version) {
    return "stale_ack";
  }

  if (latestAck.config_version > config.config_version) {
    return "pending_ack";
  }

  if (latestAck.status === "failed") {
    return "failed_ack";
  }

  return "applied";
}

export async function buildDeviceConfigStatus(config: DeviceConfigEntity) {
  const latestAck = await getLatestDeviceConfigAck(config.device_id);
  const latestPush = (
    await listMqttMessages({
      device_id: config.device_id,
      direction: "downlink",
      message_type: "config_push",
      correlation_id: `config:${config.config_version}`,
      limit: 1
    })
  )[0];

  const driftStatus = latestPush ? deriveConfigDriftStatus(config, latestAck) : "never_pushed";

  return {
    device_id: config.device_id,
    config: toDeviceConfigPayload(config),
    drift_status: driftStatus,
    desired_config_version: config.config_version,
    latest_ack: latestAck ? toDeviceConfigAckPayload(latestAck) : null,
    latest_push: latestPush ? toMqttMessagePayload(latestPush) : null,
    retry_recommended: driftStatus !== "applied"
  };
}
