import * as BackgroundFetch from 'expo-background-task';
import * as TaskManager from 'expo-task-manager';
import { isFileUploaded, markFileAsUploaded } from './db';
import { getMediaByDateRange } from './media';

const BACKGROUND_UPLOAD_TASK = 'background-upload-task';

// 注册后台任务
export const registerBackgroundUploadTask = async () => {
    try {
        // 初始化数据库表
        // initUploadTable();
        // 检查是否已经注册了任务
        const isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_UPLOAD_TASK);
        if (isRegistered) {
            await BackgroundFetch.unregisterTaskAsync(BACKGROUND_UPLOAD_TASK);
        }

        // 注册后台任务
        await BackgroundFetch.registerTaskAsync(BACKGROUND_UPLOAD_TASK, {
            minimumInterval: 15 * 60, // 15 分钟
        });

        console.log('Background task registered');
        return true;
    } catch (error) {
        console.error('Error registering background task:', error);
        return false;
    }
};

// 定义后台任务
TaskManager.defineTask(BACKGROUND_UPLOAD_TASK, async () => {
    try {
        const now = new Date();
        const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);

        // 获取最近24小时的媒体文件
        const media = await getMediaByDateRange(oneDayAgo, now);

        // 过滤已上传文件（以 uri 为唯一标识）
        const filesToUpload = [];
        for (const file of media) {
            const uploaded = await isFileUploaded(file.uri);
            if (!uploaded) filesToUpload.push(file);
        }

        if (filesToUpload.length === 0) {
            console.log('No media files to upload');
            return BackgroundFetch.BackgroundTaskResult.Success;
        }

        // 上传未上传文件
        let successCount = 0;
        for (const file of filesToUpload) {
            // 这里假设有 uploadSingleMedia 函数，或直接使用 index.ts 的 processMediaUpload
            try {
                // 你可以根据实际情况替换为自己的上传逻辑
                const { processMediaUpload } = await import('./index');
                const result = await processMediaUpload(file);
                if (result.originalSuccess) {
                    markFileAsUploaded(file.uri);
                    successCount++;
                }
            } catch (e) {
                console.error('Upload failed for', file.uri, e);
            }
        }

        console.log(`Background upload completed. Success: ${successCount}/${filesToUpload.length}`);

        return successCount > 0
            ? BackgroundFetch.BackgroundTaskResult.Success
            : BackgroundFetch.BackgroundTaskResult.Failed;
    } catch (error) {
        console.error('Background task error:', error);
        return BackgroundFetch.BackgroundTaskResult.Failed;
    }
});