import { InternalAxiosRequestConfig } from '@ohos/axios';
import { bundleManager } from '@kit.AbilityKit';
import deviceInfo from '@ohos.deviceInfo';
import { KVStore } from '../utils/KVStore';
import { APP_ID, PLATFORM, TOKEN } from '../constants/AppConstants';
import { Logger } from '../utils/Logger';
import { DeviceUtil } from '@pura/harmony-utils';
import { CHANNEL } from '../../../../BuildProfile';

/**
 * 对应 Android 的 HeaderInterceptor
 */
export const HeaderInterceptor = async (config: InternalAxiosRequestConfig): Promise<InternalAxiosRequestConfig> => {
  try {
    // 1. 获取应用信息 (对应 BuildConfig/getAppVersionName)
    const bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
    const versionName = bundleInfo.versionName;
    const bundleName = bundleInfo.name;

    // 2. 获取 Header 所需参数
    const accessToken: string = KVStore.getInstance().getSync(TOKEN, '');
    const deviceId: string = DeviceUtil.getDeviceId();
    const brand: string = deviceInfo.brand;
    const model: string = deviceInfo.productModel;

    // 3. 注入 Header (对应 mBuilder.header)
    config.headers.set('x-token', accessToken);
    config.headers.set('x-version', versionName);
    config.headers.set('x-platform', PLATFORM); // 鸿蒙平台标识(目前只有android和ios,暂不支持harmony)
    config.headers.set('x-device-id', deviceId);
    config.headers.set('x-mobile-brand', brand);
    config.headers.set('x-mobile-model', model);
    config.headers.set('x-package', bundleName);
    config.headers.set('x-base-version', versionName);
    config.headers.set('x-app-id', APP_ID);
    config.headers.set('x-channel', CHANNEL);

    // 4. 打印日志 (对应 Android 的 StringBuilder 日志)
    let logString = "\n-------------> 📤 header start<-------------\n";
      logString += `│ x-token        = ${accessToken}\n`;
      logString += `│ x-version      = ${versionName}\n`;
      logString += `│ x-platform     = ${PLATFORM}\n`;
      logString += `│ x-device-id    = ${deviceId}\n`;
      logString += `│ x-mobile-brand = ${brand}\n`;
      logString += `│ x-mobile-model = ${model}\n`;
      logString += `│ x-package      = ${bundleName}\n`;
      logString += `│ x-base-version = ${versionName}\n`;
      logString += `│ x-app-id       = ${APP_ID}\n`;
      logString += `│ x-channel      = ${CHANNEL}\n`;
      logString += "------------->    header end     <-------------";

    Logger.info('RabbitLog', logString);

  } catch (error) {
    // 对应 Android 的 catch (e: Exception)
    console.error(`HeaderInterceptor Error: ${JSON.stringify(error)}`);
  }

  return config;
}
