import type { DeviceEntity } from "../store/deviceStore";

type CapabilityProfile = {
  dynamic_qr?: boolean | {
    api_direct?: boolean;
    mqtt?: boolean;
  };
  flows?: string[];
};

export type DynamicQrFlow = "api_direct" | "mqtt";

function getProfile(device: DeviceEntity): CapabilityProfile {
  return (device.capability_profile_json || {}) as CapabilityProfile;
}

export function supportsDynamicQrFlow(device: DeviceEntity, flow: DynamicQrFlow): boolean {
  const profile = getProfile(device);
  const flows = Array.isArray(profile.flows) ? profile.flows : [];

  if (flow === "api_direct" && device.communication_mode !== "api") {
    return false;
  }

  if (flow === "mqtt" && device.communication_mode !== "mqtt") {
    return false;
  }

  if (typeof profile.dynamic_qr === "boolean") {
    return profile.dynamic_qr || flows.includes(`dynamic_qr:${flow}`);
  }

  if (profile.dynamic_qr && typeof profile.dynamic_qr === "object") {
    return Boolean(profile.dynamic_qr[flow]) || flows.includes(`dynamic_qr:${flow}`);
  }

  return flows.includes(`dynamic_qr:${flow}`);
}

export function resolveDeviceCapabilitySummary(device: DeviceEntity) {
  return {
    dynamic_qr_api_direct: supportsDynamicQrFlow(device, "api_direct"),
    dynamic_qr_mqtt: supportsDynamicQrFlow(device, "mqtt")
  };
}
