import 'dart:convert';

import 'package:autos/data/models/turn14_model.dart';
import 'package:autos/data/repositories/ebay_repository_impl.dart';
import 'package:autos/data/repositories/token_repository.dart';
import 'package:autos/data/sources/remote/api_service.dart';
import 'package:autos/domain/entities/ebay.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

/// ✅ API SERVICE PROVIDER
final ebayApiServiceProvider = Provider<ApiService>((ref) => ApiService());

/// ✅ TOKEN REPOSITORY PROVIDER
final _tokenRepositoryProvider = Provider<TokenRepository>((ref) {
  final api = ref.read(ebayApiServiceProvider);
  return TokenRepository(api);
});

/// ✅ REPOSITORY PROVIDER
final ebayRepositoryProvider = Provider<EbayRepositoryImpl>((ref) {
  final api = ref.read(ebayApiServiceProvider);
  final tokenRepo = ref.read(_tokenRepositoryProvider);
  return EbayRepositoryImpl(api, tokenRepo);
});

/// ✅ STATE NOTIFIER PROVIDER
final ebayProvider =
    StateNotifierProvider<EbayNotifier, AsyncValue<EbayEntity?>>((ref) {
  final repo = ref.read(ebayRepositoryProvider);
  return EbayNotifier(repo);
});

/// ✅ NOTIFIER
class EbayNotifier extends StateNotifier<AsyncValue<EbayEntity?>> {
  final EbayRepositoryImpl repository;

  EbayNotifier(this.repository) : super(const AsyncValue.loading()) {
    fetchStore();
  }

  /// ✅ FETCH STORE
  Future<void> fetchStore() async {
    try {
      state = const AsyncValue.loading();

      // 1️⃣ Read stored credentials
      const storage = FlutterSecureStorage();
      final saved = await storage.read(key: "turn14_credentials");
      if (saved == null) {
        state = const AsyncValue.data(null);
        return;
      }

      final decoded = jsonDecode(saved);
      final turn14 = Turn14StatusModel.fromJson(decoded);
      if (turn14.hasCredentials != true) {
        state = const AsyncValue.data(null);
        return;
      }

      // 2️⃣ Fetch store from backend
      final EbayEntity? store = await repository.getEbayStatus(); 
      // repository should now return a single EbayEntity? instead of List<EbayEntity>

      // 3️⃣ Update state
      state = AsyncValue.data(store);
    } catch (e, st) {
      debugPrint("❌ EBAY FETCH ERROR: $e");
      state = AsyncValue.error(e, st);
    }
  }

}
