// ignore_for_file: curly_braces_in_flow_control_structures, prefer_is_empty

import 'dart:async';
import 'dart:developer';

import 'package:hub/features/backend/index.dart';
import 'package:hub/features/local/data/repositories/locals_repository_impl.dart';
import 'package:hub/features/module/index.dart';

abstract class LicenseRemoteDataSource {
  Future<bool> fetchLicenses(bool isNewVersion);
  Future<bool> cleanLicense();
  Future<void> processLicense();
}

class LicenseRemoteDataSourceImpl implements LicenseRemoteDataSource {
  Api? _api;

  static final LicenseRemoteDataSourceImpl _instance =
      LicenseRemoteDataSourceImpl._internal();

  factory LicenseRemoteDataSourceImpl(Api api) {
    _instance._api ??= api;
    return _instance;
  }

  LicenseRemoteDataSourceImpl._internal();

  @override
  Future<void> processLicense() async {}

  @override
  Future<bool> cleanLicense() async {
    try {
      LocalsRepositoryImpl.license.add(false);
      return true;
    } catch (e, s) {
      log('Erro ao limpar licenças: $e', stackTrace: s);
      return false;
    }
  }

  @override
  Future<bool> fetchLicenses(bool isNewVersion) async {
    log('Fetching licenses...');
    try {
      final response = await _instance._api?.getLicense();
      final dynamic responseBody = response!.jsonBody;

      if (responseBody == []) {
        return true;
      } else if (response.jsonBody is! List<dynamic>) {
        late final String error;
        if (response.jsonBody is Map<String, dynamic>)
          error = response.jsonBody['error_msg'];
        else
          error = 'Erro desconhecido';

        throw Exception('Erro ao consultar licenças: $error');
      }

      List<Future<void>> saveOperations = [];
      for (var element in responseBody) {
        if (licenseContainsKey(element['key'])) {
          saveOperations.add(_saveModule(element));
        }
      }
      await Future.wait(saveOperations);
      return true;
    } catch (e, s) {
      log('Erro ao obter licenças: $e', stackTrace: s);
      // return  await setupLicense(DatabaseStorage.database, isNewVersion);
      return true;
    }
  }

  Future<void> waitForSaveCompletion() async {
    await LocalsRepositoryImpl.stream;
  }

  static bool licenseContainsKey(final String key) {
    return LicenseKeys.values.map((e) => e.value).toList().contains(key);
  }

  static Future<void> _saveModule(final dynamic body) async {
    if (body is! Map<String, dynamic>) return;
    await LicenseRepositoryImpl().setModule(body['key'], body);
  }
}
