import 'dart:convert';

import 'package:autos/data/models/turn14_model.dart';
import 'package:autos/data/repositories/turn14_repository_impl.dart';
import 'package:autos/data/sources/remote/api_service.dart';
import 'package:autos/domain/entities/turn14.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';


/// ------------------------------------------------------------
///  Service Providers
/// ------------------------------------------------------------

final turn14ApiServiceProvider =
    Provider<ApiService>((ref) => ApiService());

final turn14RepositoryProvider = Provider<Turn14RepositoryImpl>((ref) {
  return Turn14RepositoryImpl(ref.read(turn14ApiServiceProvider));
});


/// ------------------------------------------------------------
///  Turn14 Notifier
/// ------------------------------------------------------------

class Turn14Notifier extends StateNotifier<AsyncValue<Turn14Entity?>> {
  final Turn14RepositoryImpl repository;
  final _storage = const FlutterSecureStorage();

  static const _turn14StorageKey = "turn14_credentials";

  Turn14Notifier(this.repository) : super(const AsyncValue.data(null));

  /// Save Turn14 credentials
  Future<void> saveCredentials({
    required String userId,
    required String clientId,
    required String clientSecret,
  }) async {
    state = const AsyncValue.loading();

    try {
      final response = await repository.save(
        userId: userId,
        clientId: clientId,
        clientSecret: clientSecret,
      );

      // if (response is Turn14Response) {
      //   await _storage.write(
      //     key: _turn14StorageKey,
      //     value: response.toRawJson(),
      //   );
      // }

      state = AsyncValue.data(response);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }

  /// Load saved Turn14 credentials
  Future<void> loadSavedCredentials() async {
    final saved = await _storage.read(key: _turn14StorageKey);
    if (saved == null) return;

    final decoded = jsonDecode(saved);
    final model = Turn14Response.fromJson(decoded);

    state = AsyncValue.data(model as Turn14Entity?);
  }

  /// Clear saved Turn14 data
  Future<void> clear() async {
    await _storage.delete(key: _turn14StorageKey);
    state = const AsyncValue.data(null);
  }
}


/// ------------------------------------------------------------
///  Riverpod Provider
/// ------------------------------------------------------------

final turn14Provider =
    StateNotifierProvider<Turn14Notifier, AsyncValue<Turn14Entity?>>((ref) {
  final repository = ref.read(turn14RepositoryProvider);
  return Turn14Notifier(repository);
});
