import { uploadFileApi, UPLOAD_BIZ_TYPE } from '@/api/minio';
import type { FileItem } from './types';

export function stringToArray(str?: string): number[] | undefined {
  if (!str) return undefined;
  return JSON.parse('[' + str + ']');
}

export function unformatAttachment(file?: string) {
  if (!file) return undefined;
  const fileData: FileItem[] = JSON.parse(file);
  return fileData;
}

export const formatAttachment = async (data: FileItem) => {
  if (!data.file) return data;
  const uuid = Math.random().toString(36).substring(2, 9);
  const timestamp = Date.now().toString();
  const random = Math.random().toString(36).substring(2, 4);
  const fileName = data.fileName;
  const res = await uploadFileApi({
    bizType: UPLOAD_BIZ_TYPE.ATTACHMENT,
    fileName: `${uuid}-${timestamp}-${random}`,
    file: data.file,
  });
  const fileType = data.fileType;
  const fileSize = data.fileSize;
  const fileId = data.fileId;
  const fileUrl = res.url;
  return {
    fileName,
    fileType,
    fileSize,
    fileUrl,
    fileId,
  };
};

export const formatAttachmentList = async (data: FileItem[]) => {
  if (!data || data.length === 0) return data;
  const res = await Promise.all(
    data.map(async (item) => {
      const res = await formatAttachment(item);
      return res;
    }),
  );
  return res;
};
