import 'dart:convert';
import 'package:autos/core/constants/api_endpoints.dart';
import 'package:autos/data/models/brands_model.dart';
import 'package:autos/data/sources/remote/api_service.dart';
import 'package:autos/domain/entities/brands.dart';
import 'package:dio/dio.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:autos/data/models/user_model.dart';

abstract class BrandsRepository {
  Future<List<BrandEntity>> getBrands();
}

class BrandsRepositoryImpl implements BrandsRepository {
  final ApiService _apiService;
  final _storage = const FlutterSecureStorage();
  static const _userKey = 'logged_in_user';

  BrandsRepositoryImpl(this._apiService);

  /// ✅ ALWAYS CALL TOKEN API (FORCE REFRESH)
  Future<String> getTurn14AccessToken() async {
    final jsonString = await _storage.read(key: _userKey);
    if (jsonString == null) {
      throw Exception("User not found. Please login again.");
    }

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

    final response = await _apiService.post(ApiEndpoints.getToken, {
      "userid": user.id,
    });

    final data = response.data;

    String token;

    if (data["code"] == "TOKEN_UPDATED") {
      // ✅ New token returned
      token = data["access_token"];
      await _storage.write(key: 'turn14_token', value: token);
    } else if (data["code"] == "TOKEN_VALID") {
      // ✅ Token still valid, read from storage
      token = data["access_token"];
      await _storage.write(key: 'turn14_token', value: token);
      token = await _storage.read(key: 'turn14_token') ?? '';
      if (token.isEmpty) {
        throw Exception("Token missing in storage");
      }
    } else {
      throw Exception(data["message"]);
    }

    debugPrint("Turn14 Token: $token");
    return token;
  }

  /// ✅ FETCH BRANDS USING FRESH TOKEN EVERY TIME
  @override
  Future<List<BrandEntity>> getBrands() async {
    try {
      final token = await getTurn14AccessToken();

      final response = await _apiService.get(
        '/v1/brands',
        overrideBaseUrl: 'https://turn14.data4autos.com',
        headers: {
          'Authorization': 'Bearer $token',
          'Content-Type': 'application/json',
        },
      );

      if (response.statusCode != 200) {
        throw Exception("Server error: ${response.statusCode}");
      }

      final data = response.data;

      if (data is! Map || data["data"] == null) {
        throw Exception("Invalid API response");
      }

      final list = data["data"] as List;

      return list.map((json) => Brand.fromJson(json).toEntity()).toList();
    } on DioException catch (e) {
      throw Exception("Network error: ${e.response?.data ?? e.message}");
    } catch (e) {
      throw Exception("Unexpected error: $e");
    }
  }

  /// ✅ BULK INSERT SELECTED BRANDS
  Future<Map<String, dynamic>> saveSelectedBrands({
    required String userId,
    required List<BrandEntity> brands,
  }) async {
    try {
      final payload = {
        "userid": userId,
        "brands": brands
            .map(
              (brand) => {
                "id": brand.id.toString(),
                "name": brand.name,
                "logo": brand.logo,
                "dropship": brand.dropship,
              },
            )
            .toList(),
      };

      final response = await _apiService.postWithOptions(
        "/api/brands/bulk-insert",
        overrideBaseUrl: "https://ebay.backend.data4autos.com",
        data: payload,
      );

      return response.data;
    } on DioException catch (e) {
      throw Exception("Save failed: ${e.response?.data ?? e.message}");
    } catch (e) {
      throw Exception("Unexpected error: $e");
    }
  }
}
