// Background Sync Service using expo-task-manager

import * as TaskManager from 'expo-task-manager';
import { syncAllFeeds, getFeedsDueForSync } from './sync-service';
import { useFeedStore } from '@/stores/feed-store';

const BACKGROUND_SYNC_TASK_NAME = 'BACKGROUND_SYNC_TASK';
const BACKGROUND_SYNC_INTERVAL = 15; // minutes

// Task manager result types
enum BackgroundFetchResult {
  NoData = 'noData',
  NewData = 'newData',
  Failed = 'failed',
}

// Define the background task
TaskManager.defineTask(BACKGROUND_SYNC_TASK_NAME, async () => {
  try {
    console.log('[Background] Starting background sync...');
    
    const subscriptions = useFeedStore.getState().subscriptions;
    if (subscriptions.length === 0) {
      console.log('[Background] No subscriptions to sync');
      return BackgroundFetchResult.NoData;
    }

    const result = await syncAllFeeds();
    
    if (result.success) {
      console.log(`[Background] Synced ${result.totalItemsSynced} items`);
      return BackgroundFetchResult.NewData;
    } else {
      console.log('[Background] Sync completed with errors');
      return BackgroundFetchResult.Failed;
    }
  } catch (error) {
    console.error('[Background] Sync error:', error);
    return BackgroundFetchResult.Failed;
  }
});

// Register background fetch task
export async function registerBackgroundSync(): Promise<boolean> {
  try {
    const task = TaskManager.defineTask(BACKGROUND_SYNC_TASK_NAME, async () => {
      try {
        console.log('[Background] Starting background sync...');
        
        const subscriptions = useFeedStore.getState().subscriptions;
        if (subscriptions.length === 0) {
          console.log('[Background] No subscriptions to sync');
          return;
        }

        const result = await syncAllFeeds();
        console.log(`[Background] Synced ${result.totalItemsSynced} items`);
      } catch (error) {
        console.error('[Background] Sync error:', error);
      }
    });

    const status = await TaskManager.isTaskRegisteredAsync(BACKGROUND_SYNC_TASK_NAME);
    if (status) {
      console.log('[Background] Background sync already registered');
      return true;
    }
    
    console.log('[Background] Background sync registered successfully');
    return true;
  } catch (error) {
    console.error('[Background] Failed to register background sync:', error);
    return false;
  }
}

// Unregister background fetch task
export async function unregisterBackgroundSync(): Promise<void> {
  try {
    await TaskManager.unregisterTaskAsync(BACKGROUND_SYNC_TASK_NAME);
    console.log('[Background] Background sync unregistered');
  } catch (error) {
    console.error('[Background] Failed to unregister:', error);
  }
}

// Check if background sync task is registered
export async function isBackgroundSyncRegistered(): Promise<boolean> {
  return TaskManager.isTaskRegisteredAsync(BACKGROUND_SYNC_TASK_NAME);
}