import { AxiosResponse } from '@ohos/axios';
import { AESDecrypt, DEBUG_BASE_URL, RELEASE_BASE_URL } from '../constants/AppConstants';
import { CryptoHelper, CryptoUtil, AES, StrUtil } from '@pura/harmony-utils';

export class ResponseInterceptor {
  private static readonly TAG: string = "RabbitLog_Response";

  static async responseHandler(response: AxiosResponse): Promise<AxiosResponse> {
    const url: string = response.config.baseURL ?? "";

    const isDebug: boolean = true;
    const baseUrl: string = isDebug ? DEBUG_BASE_URL : RELEASE_BASE_URL;

    // 1. 过滤非业务接口
    if (!url.startsWith(baseUrl)) {
      return response;
    }

    try{
      // 2. 检查 Content-Type
      let contentType = response.headers['content-type'] as string;
      let dataString: string = '';
      // 3. 解析响应体 (Axios 默认已将 data 转为对象)
      if (StrUtil.isNotEmpty(contentType) && contentType?.includes("application/json") && response.data !== null) {
        let isEncrypt = response.data['encrypt'] as boolean
        dataString = response.data['data'] as string;
        if (isEncrypt) {
          console.info(`[${ResponseInterceptor.TAG}] 是否需要解密: 需要`);
          dataString = ResponseInterceptor.decryptNormal(dataString, AESDecrypt);
        } else {
          console.info(`[${ResponseInterceptor.TAG}] 是否需要解密: 不需要`);
          let newResponse: Record<string, Object> = {
            'code': 0,
            'data': dataString
          }
          dataString = JSON.stringify(newResponse)
        }
      }
      response.data = JSON.parse(dataString);

      // 兼容某些接口 400 情况
      if (response.status === 400) {
        response.status = 200;
      }
      return response;
    } catch (e) {
      const err = e as Error;
      console.error(`[${ResponseInterceptor.TAG}] 解密失败: ${err.message}`);
      return Promise.reject(response);
    }
  }

  private static decryptNormal(encryptStr: string, key: string): string {
    let dataBlob = CryptoHelper.strToDataBlob(encryptStr, 'base64');
    let keyBytes = CryptoUtil.getConvertSymKeySync('AES256', key, 'utf-8')
    let ivParams= CryptoUtil.getIvParamsSpec(key.substring(0, 16), 'utf-8')
    let plain = AES.decryptCBCSync(dataBlob, keyBytes, ivParams);
    return StrUtil.unit8ArrayToStr(plain.data);
  }
}
