// plugins/scheduler.client.ts
import { useClinicStore } from '@/stores/clinicStore';
import { useDoctorStore } from '@/stores/doctorStore';

export default defineNuxtPlugin((nuxtApp) => {
  // We only want this to run on the client side (kiosks)
  if (process.server) return;

  const CHECK_INTERVAL = 60 * 1000; // Check every minute
  let isSyncing = false;

  const checkSync = async () => {
    if (isSyncing) return;

    try {
      const clinicStore = useClinicStore();
      const doctorStore = useDoctorStore();

      const now = new Date();
      
      // We target 2:00 AM. 
      // If it's between 2:00 and 2:05, and store says sync is needed, we trigger it.
      // This window prevents missing it if the kiosk is slightly off or interval skips.
      const isSyncWindow = now.getHours() === 2 && now.getMinutes() < 5;
      
      const clinicSyncNeeded = clinicStore.isSyncNeeded();
      const doctorSyncNeeded = doctorStore.isSyncNeeded();

      if (isSyncWindow && (clinicSyncNeeded || doctorSyncNeeded)) {
        console.log('⏰ [scheduler] 2 AM Sync window detected. Triggering sync...');
        isSyncing = true;

        // 1. Sync Clinics
        console.log('🔄 [scheduler] Syncing clinics...');
        await clinicStore.fetchRegulerClinics(true);
        
        // 2. Sync Doctors after clinics are ready
        console.log('🔄 [scheduler] Syncing doctors...');
        const allClinics = clinicStore.clinics;
        await doctorStore.syncAllDoctors(allClinics);
        
        console.log('✅ [scheduler] Daily 2 AM sync completed successfully.');
      }
    } catch (error) {
      console.error('❌ [scheduler] Error during scheduled sync:', error);
    } finally {
      isSyncing = false;
    }
  };

  // Run initial check on site load
  setTimeout(checkSync, 5000); // Wait 5s for stores to hydrate

  // Set interval for periodic check
  setInterval(checkSync, CHECK_INTERVAL);
  
  console.log('🕒 [scheduler] 2 AM Sync Scheduler initialized.');
});
