import { supabase } from './supabase';
import * as offline from './offlineStorage';
import { todayISO } from '../utils/date';

// Must match authService.js
const USE_OFFLINE = true;

const DEFAULT_TIMES = ['06:00','06:30','07:00','07:30','08:00','12:00','17:00','18:00','19:00','20:00','21:00'];
const DEFAULT_DURATIONS = [10, 15, 20, 15, 30, 10, 15, 20, 10, 15];

export async function getHabits(identityId) {
  if (USE_OFFLINE) {
    const habits = await offline.getAll('habits', { identity_id: identityId });

    // Auto-migrate old habits that are missing best_time/duration
    let needsSave = false;
    const migrated = habits.map((h, i) => {
      if (h.best_time && h.duration) return h;
      needsSave = true;
      return {
        ...h,
        best_time: h.best_time || DEFAULT_TIMES[i % DEFAULT_TIMES.length],
        duration: h.duration || DEFAULT_DURATIONS[i % DEFAULT_DURATIONS.length],
        frequency: h.frequency || 'Every day',
        category: h.category || ['Discipline','Body','Mind','Emotion','Health'][i % 5],
        difficulty: h.difficulty || (i < 2 ? 'Easy' : 'Medium'),
      };
    });

    // Persist the migration
    if (needsSave) {
      for (const h of migrated) {
        await offline.update('habits', { id: h.id }, {
          best_time: h.best_time,
          duration: h.duration,
          frequency: h.frequency,
          category: h.category,
          difficulty: h.difficulty,
        });
      }
    }

    return migrated;
  }

  const { data, error } = await supabase
    .from('habits')
    .select('*')
    .eq('identity_id', identityId);

  if (error) throw error;
  return data || [];
}

export async function getTodayHabitLogs(habitIds) {
  if (!habitIds.length) return {};
  const today = todayISO();

  if (USE_OFFLINE) {
    const allLogs = await offline.getAll('habit_logs');
    const logs = {};
    allLogs.forEach((log) => {
      if (habitIds.includes(log.habit_id) && log.date === today) {
        logs[log.habit_id] = log.completed;
      }
    });
    return logs;
  }

  const { data, error } = await supabase
    .from('habit_logs')
    .select('*')
    .in('habit_id', habitIds)
    .eq('date', today);

  if (error) throw error;

  const logs = {};
  (data || []).forEach((log) => {
    logs[log.habit_id] = log.completed;
  });
  return logs;
}

export async function saveHabitLog(habitId, completed) {
  const today = todayISO();

  if (USE_OFFLINE) {
    await offline.upsert(
      'habit_logs',
      { habit_id: habitId, date: today },
      { completed }
    );
    return;
  }

  const { data: existing } = await supabase
    .from('habit_logs')
    .select('id')
    .eq('habit_id', habitId)
    .eq('date', today)
    .maybeSingle();

  if (existing) {
    const { error } = await supabase
      .from('habit_logs')
      .update({ completed })
      .eq('id', existing.id);
    if (error) throw error;
  } else {
    const { error } = await supabase
      .from('habit_logs')
      .insert({ habit_id: habitId, date: today, completed });
    if (error) throw error;
  }
}
