/**
 * BUG数据提交工具层
 * 
 * Copyright © 2025 imengyu.top imengyu-bugreport-server
 */

import Constants, { isProd } from '@/common/config/AppCofig';
import type { BugDetailDeviceInfo, BugReporterAbstractionLayer } from '../index'

const tagString = '[BugReporter] ';
const errStorageClientDataKey = 'BugReporterClientData';

export class BugReporterAbstractionUniapp implements BugReporterAbstractionLayer {
  log(str: string): void {
    console.log(tagString + str);
  }
  async getDeviceInfo(): Promise<BugDetailDeviceInfo> {
    let dataStorage = await this.getStorage(errStorageClientDataKey);
    if (!dataStorage) {
      const res = await uni.getSystemInfo({}) as unknown as Record<string, unknown>;

      dataStorage = {
        deviceName: res.mode + '/' + res.model + '/' + res.brand + '/' + res.pixelRatio,
        deviceVersion: res.system + '/' + res.version + '/SDKVersion: ' + res.SDKVersion,
        appVersion: Constants.version,
      } as BugDetailDeviceInfo;
      
      await this.setStorage(errStorageClientDataKey, dataStorage);
    }
    return dataStorage as BugDetailDeviceInfo;
  }
  async enable(): Promise<boolean> {
    return isProd;
  }
  async doPost(url: string, body: unknown): Promise<void> {
    await uni.request({
      url,
      data: body as AnyObject,
      method: 'POST'
    });
  }
  async getStorage(key: string): Promise<unknown> {
    try {
      const str = await uni.getStorage({ key }) as unknown as Record<string, string>;
      return str.data ? JSON.parse(str.data) : null;
    } catch {
      return null;
    }
  }
  async setStorage(key: string, value: unknown): Promise<void> {
    await uni.setStorage({ key, data: JSON.stringify(value) });
  }
  async reomveStorage(key: string): Promise<void> {
    await uni.removeStorage({ key });
  }
}

