import 'dart:convert';
import 'package:autos/core/constants/api_endpoints.dart';
import 'package:autos/data/models/user_model.dart';
import 'package:autos/data/sources/remote/api_service.dart';
import 'package:autos/domain/entities/ebay.dart';
import 'package:autos/data/repositories/token_repository.dart';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

abstract class EbayRepository {
  /// Return a single store or null if none exists
  Future<EbayEntity?> getEbayStatus();
}

class EbayRepositoryImpl implements EbayRepository {
  final ApiService _apiService;
  final TokenRepository _tokenRepository;
  final FlutterSecureStorage _storage = const FlutterSecureStorage();
  static const _userKey = 'logged_in_user';

  EbayRepositoryImpl(this._apiService, this._tokenRepository);

  @override
  Future<EbayEntity?> getEbayStatus() async {
    // 1️⃣ Read logged-in user
    final jsonString = await _storage.read(key: _userKey);
    if (jsonString == null) return null;

    final user = UserModel.fromJson(jsonDecode(jsonString));

    // 2️⃣ Get valid token
    final token = await _tokenRepository.getValidToken(user.id);

    // 3️⃣ Call eBay API
    final response = await _apiService.postWithOptions(
      ApiEndpoints.checkstorestatus,
      data: {"userid": user.id},
      headers: {"Authorization": "Bearer $token"},
    );

    debugPrint('🟢 Ebay API Raw Response: ${response.data}');

    // 4️⃣ Extract 'store' from response
    final data = response.data;
    if (data == null || data is! Map<String, dynamic>) return null;

    final storeJson = data['store'];
    if (storeJson == null || storeJson is! Map<String, dynamic>) return null;

    // 5️⃣ Convert to entity
    final storeEntity = EbayEntity.fromJson(storeJson);
    return storeEntity;
  }
}
