import 'dart:developer';

import 'package:hub/features/module/data/data_sources/index.dart';
import 'package:hub/features/module/domain/index.dart';
import 'package:hub/features/storage/index.dart';
import 'package:sqflite/sqflite.dart';

import '../../../backend/index.dart';

typedef LicenseStatus = bool;

class LicenseRepositoryImpl implements LicenseRepository {
  late final Database database;
  late final Api api;
  late final LicenseLocalDataSource localDataSource;
  late final LicenseRemoteDataSource remoteDataSource;

  LicenseRepositoryImpl([Database? database, Api? api])
      : database = database ?? DatabaseService.database,
        api = api ?? PhpGroup() {
    localDataSource = LicenseLocalDataSourceImpl(this.database);
    remoteDataSource = LicenseRemoteDataSourceImpl(this.api);
  }

  @override
  Future<bool> updateLicense() async {
    log('updateLicense');
    bool result = false;
    final bool isNewVersion = await localDataSource.isNewVersion();

    if (isNewVersion) {
      await localDataSource.setupLicense(isNewVersion);
      result = await remoteDataSource.fetchLicenses(isNewVersion);
    } else {
      result = await localDataSource.setupLicense(isNewVersion);
    }

    return result;
  }

  @override
  Future<bool> cleanLicense() async {
    return await remoteDataSource.cleanLicense();
  }

  @override
  Future<String?> getModule(String key) async {
    final response = await localDataSource.get(key);
    return response;
  }

  @override
  Future<bool> setModule<T>(String key, T value) async {
    return await localDataSource.set(key, value);
  }

  @override
  Future<List<String>> getLicense() async {
    return await localDataSource.getLicense();
  }

  @override
  Future<bool> resetLicense() async {
    bool result = false;
    final bool isNewVersion = await localDataSource.isNewVersion();
    result = await localDataSource.setupLicense(isNewVersion);
    return result;
  }
}
