import { getUploadUrl, confirmUpload } from '../background-uploader/api';
import { uploadFile } from '../background-uploader/uploader';
import { compressImage } from '../image-process/imageCompress';
import { ExtendedAsset } from '../background-uploader/types';

// 提取视频的首帧进行压缩并上传
export const uploadVideoThumbnail = async (asset: ExtendedAsset) => {
    try {
        const manipResult = await compressImage(asset.uri);
        const response = await fetch(manipResult.uri);
        const blob = await response.blob();
        const filename = asset.filename ?
            `compressed_${asset.filename}` :
            `image_${Date.now()}_compressed.jpg`;
        const compressedFile = new File([blob], filename, { type: 'image/jpeg' });

        const { upload_url, file_id } = await getUploadUrl(compressedFile, {
            originalUri: asset.uri,
            creationTime: asset.creationTime,
            mediaType: 'image',
            isCompressed: true
        });

        await uploadFile(compressedFile, upload_url);
        await confirmUpload(file_id);

        return { success: true, file_id };
    } catch (error) {
        return { success: false, error };
    }
};
