import 'dart:developer';

import 'package:hub/features/storage/constants/locals_constants.dart';
import 'package:hub/features/storage/index.dart';
import 'package:sqflite/sqflite.dart';

abstract class LocalsLocalDataSource implements BaseStorage {}

class LocalsLocalDataSourceImpl implements LocalsLocalDataSource {
  static final LocalsLocalDataSourceImpl _instance =
      LocalsLocalDataSourceImpl._internal();
  factory LocalsLocalDataSourceImpl() => _instance;
  LocalsLocalDataSourceImpl._internal();

  bool _isInitialized = false;

  @override
  Future<void> init() async {
    if (_isInitialized) return;
    await DatabaseService.instance.init();
    _isInitialized = true;
  }

  @override
  Future<String?> get(String key) async {
    final String? local =
        await StorageHelper().get(ProfileStorageKey.clientUUID.key);
    if (local == null) {
      return null;
    }
    var response = await DatabaseService.database.query(
        LocalsConstants.tableLocalsKeychain,
        where: 'key = ? AND local = ?',
        whereArgs: [key, local]);
    if (response.isEmpty) {
      return null;
    }
    return response.first['value'].toString();
  }

  @override
  Future<void> set<T>(String key, T value) async {
    try {
      var date = DateTime.now().toIso8601String();
      final String? local =
          await StorageHelper().get(ProfileStorageKey.clientUUID.key);

      await DatabaseService.database.insert(
        LocalsConstants.tableLocalsKeychain,
        {
          'key': key,
          'value': value.toString(),
          'type': 'local',
          'updateAt': date,
          'resolvedAt': date,
          'createdAt': date,
          'local': local
        },
        conflictAlgorithm: ConflictAlgorithm.replace,
      );
    } catch (e, s) {}
  }

  @override
  Future<void> delete(String key) async {
    final String? local =
        await StorageHelper().get(ProfileStorageKey.clientUUID.key);
    await DatabaseService.database.delete(LocalsConstants.tableLocalsKeychain,
        where: 'key = ? AND local = ?', whereArgs: [key, local]);
  }

  @override
  Future<void> clearAll() async {
    try {
      await DatabaseService.database
          .delete(LocalsConstants.tableLocalsKeychain);
    } catch (e, s) {
      log('() => clearAll keychain: $e', stackTrace: s);
    }
  }
}
