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

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

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

export const formatImage = async (data: ImageItem) => {
  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 res = await uploadFileApi({
    bizType: UPLOAD_BIZ_TYPE.ATTACHMENT,
    fileName: `${uuid}-${timestamp}-${random}`,
    file: data.file,
  });
  return res.url;
};

export const formatImageList = async (data: Array<ImageItem> | undefined) => {
  if (!data || data.length === 0) return null;
  const res = await Promise.all(
    data.map(async (item) => {
      if (!item.file) return item.url;
      const res = await formatImage(item);
      return res;
    }),
  );
  return res;
};
