import 'package:hive_flutter/hive_flutter.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class Settings {
  static const box = "settings";
  static get(String key, {String? defaultValue}) {
    Hive.box(box).get(key, defaultValue: defaultValue);
  }

  Future<Map<String, dynamic>?> getFresh(String key, {String? userId}) async {
    SupabaseClient supabase = Supabase.instance.client;
    final session = supabase.auth.currentSession;
    if (session != null) {
      final response = await Supabase.instance.client
          .from('settings')
          .select()
          .eq('user_id', userId ?? session.user.id)
          .eq('field', key)
          .single();
      return response as Map<String, dynamic>?;
    }
  }

  static put(String key, value) {
    Hive.box(box).put(key, value);
    SupabaseClient supabase = Supabase.instance.client;
    if (supabase.auth.currentSession != null) {
      upsertSettings(
          userid: supabase.auth.currentSession!.user.id,
          field: key,
          value: value);
    }
  }

  static Future<void> upsertSettings({userid, field, value}) async {
    final response = await Supabase.instance.client.from('settings').upsert(
      {'user_id': userid, 'field': field, 'value': value},
      onConflict: 'user_id,field',
    ).select();
    print('settings: upsertsettings: response: $response');
  }

  static delete(String key) => Hive.box(box).delete(key);
  static clear() => Hive.box(box).clear();
  static close() => Hive.box(box).close();
  static isOpen() => Hive.box(box).isOpen;
  static openBox() => Hive.openBox(box);
}
