import * as SecureStore from 'expo-secure-store';

const QUEUE_KEY = 'uploadQueue';

export type UploadItem = {
    uri: string;
    filename: string;
};

// 存储队列
export const saveUploadQueue = async (queue: UploadItem[]) => {
    await SecureStore.setItemAsync(QUEUE_KEY, JSON.stringify(queue));
};

// 获取队列
export const getUploadQueue = async (): Promise<UploadItem[]> => {
    const data = await SecureStore.getItemAsync(QUEUE_KEY);
    return data ? JSON.parse(data) : [];
};

// 移除已上传项
export const removeFromQueue = async (uri: string) => {
    const queue = await getUploadQueue();
    const newQueue = queue.filter(item => item.uri !== uri);
    await saveUploadQueue(newQueue);
};

export const uploadMediaFile = async (asset: any) => {
    const uri = asset.uri;
    const filename = uri.split('/').pop() || 'file.jpg';
    const type =
        asset.mediaType === 'photo'
            ? `image/${filename.split('.').pop()}`
            : `video/${filename.split('.').pop()}`;

    const formData = new FormData();
    formData.append('file', { uri, name: filename, type } as any);

    await getUploadUrl({
        ...formData,
        name: filename,
        type,
        size: asset.fileSize
    }, {}).then((res) => {
        confirmUpload(res.file_id).then((confirmRes) => {
            addMaterial(res.file_id, confirmRes.file_id)
        }).catch((error) => {
            console.log(error);
        })
    }).catch((error) => {
        console.log(error);
    })
};

// 获取上传URL
const getUploadUrl = async (file: File, metadata: Record<string, any> = {}): Promise<UploadUrlResponse> => {
    const body = {
        filename: file.name,
        content_type: file.type,
        file_size: file.size,
        metadata: {
            ...metadata,
            originalName: file.name,
            fileType: 'image',
            isCompressed: metadata.isCompressed || 'false',
        },
    };
    return await fetchApi<UploadUrlResponse>("/file/generate-upload-url", {
        method: 'POST',
        body: JSON.stringify(body)
    });
};

// 向服务端confirm上传
const confirmUpload = async (file_id: string): Promise<ConfirmUpload> => await fetchApi<ConfirmUpload>('/file/confirm-upload', {
    method: 'POST',
    body: JSON.stringify({
        file_id
    })
});

// 新增素材
const addMaterial = async (file: string, compressFile: string) => {
    await fetchApi('/material', {
        method: 'POST',
        body: JSON.stringify([{
            "file_id": file,
            "preview_file_id": compressFile
        }])
    }).catch((error) => {
        // console.log(error);
    })
}