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

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

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

  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;
  }
}
