import { rebootSecurityBoxBeidianApi, rebootSecurityBoxNingTechApi, turnCircuitStatusBeidianApi, turnCircuitStatusNingTechApi, type NdmSecurityBoxResultVO } from '@/apis';
import { objectEntries } from '@vueuse/core';

const UNSUPPORTED_SECURITY_BOX_VENDOR = '不支持的安防箱厂商';

export const SECURITY_BOX_VENDOR_LITERALS = {
  beidian: 'beidian',
  ningtech: 'ningtech',
} as const;

export type SecurityBoxVendor = keyof typeof SECURITY_BOX_VENDOR_LITERALS;

export const resolveSecurityBoxVendor = (vendor?: string) => {
  const entry = objectEntries(SECURITY_BOX_VENDOR_LITERALS).find(([, value]) => value === vendor);
  return entry?.at(0);
};

export const normalizeSecurityBoxWriteCommunity = (ndmDevice: NdmSecurityBoxResultVO, vendor?: string) => {
  const resolved = resolveSecurityBoxVendor(vendor);
  if (resolved === SECURITY_BOX_VENDOR_LITERALS.beidian) {
    const community = ndmDevice.community;
    if (!community) throw new Error('团体字符串不存在');
    return community;
  }
  if (resolved === SECURITY_BOX_VENDOR_LITERALS.ningtech) {
    const community = ndmDevice.writeCommunity;
    if (!community) throw new Error('团体字符串(写)不存在');
    return community;
  }
  throw new Error(UNSUPPORTED_SECURITY_BOX_VENDOR);
};

export const normalizeSecurityBoxCircuitIndex = (index: number, vendor?: string) => {
  const resolved = resolveSecurityBoxVendor(vendor);
  if (resolved === SECURITY_BOX_VENDOR_LITERALS.beidian) {
    return index;
  }
  if (resolved === SECURITY_BOX_VENDOR_LITERALS.ningtech) {
    return index + 1;
  }
  throw new Error(UNSUPPORTED_SECURITY_BOX_VENDOR);
};

export const dispatchTurnCircuitStatusApi = (vendor?: string) => {
  const resolved = resolveSecurityBoxVendor(vendor);
  if (resolved === SECURITY_BOX_VENDOR_LITERALS.beidian) {
    return turnCircuitStatusBeidianApi;
  }
  if (resolved === SECURITY_BOX_VENDOR_LITERALS.ningtech) {
    return turnCircuitStatusNingTechApi;
  }
  throw new Error(UNSUPPORTED_SECURITY_BOX_VENDOR);
};

export const dispatchRebootSecurityBoxApi = (vendor?: string) => {
  const resolved = resolveSecurityBoxVendor(vendor);
  if (resolved === SECURITY_BOX_VENDOR_LITERALS.beidian) {
    return rebootSecurityBoxBeidianApi;
  }
  if (resolved === SECURITY_BOX_VENDOR_LITERALS.ningtech) {
    return rebootSecurityBoxNingTechApi;
  }
  throw new Error(UNSUPPORTED_SECURITY_BOX_VENDOR);
};
