import 'dart:developer';

import 'package:hub/features/storage/constants/profile_constants.dart';
import 'package:hub/features/storage/index.dart';
import 'package:hub/shared/constants/index.dart';

import 'package:sqflite/sqflite.dart';

abstract class ProfileLocalDataSource implements DatabaseStorage {}

class ProfileLocalDataSourceImpl implements ProfileLocalDataSource {
  static final ProfileLocalDataSourceImpl _instance =
      ProfileLocalDataSourceImpl._internal();
  factory ProfileLocalDataSourceImpl() => _instance;
  ProfileLocalDataSourceImpl._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 {
    var response = await DatabaseService.database
        .query(tableKeychain, where: 'key = ?', whereArgs: [key]);
    if (response.isEmpty) {
      return null;
    }
    // log('() => get keychain: $key : ${response.first['value']}');
    return response.first['value'].toString();
  }

  @override
  Future<void> set<T>(String key, T value) async {
    var date = DateTime.now().toIso8601String();
    await DatabaseService.database.insert(
        tableKeychain,
        {
          'key': key,
          'value': value.toString(),
          'type': 'local',
          'updateAt': date,
          'resolvedAt': date,
          'createdAt': date,
        },
        conflictAlgorithm: ConflictAlgorithm.replace);
    // log('() => set keychain: $key : $value');
  }

  @override
  Future<void> delete(String key) async {
    await DatabaseService.database
        .delete(tableKeychain, where: 'key = ?', whereArgs: [key]);
  }

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