import 'dart:convert';
import 'package:http/http.dart' as http;
import '/core/constants.dart';
import '/data/models/contact_model.dart';
import '/domain/services/api_service.dart';

class ContactRepository {
  final http.Client _client = http.Client();
  final ApiService _apiService = ApiService();

  Future<List<Contact>> fetchChatContacts() async {
    final token = await _apiService.getAccessToken();
    if (token == null) {
      throw Exception('No access token');
    }

    final response = await _client.get(
      Uri.parse('${AppConstants.baseUrl}/users/chats'),
      headers: {
        'Authorization': 'Bearer $token',
        'Content-Type': 'application/json',
      },
    );

    if (response.statusCode == 200) {
      final List<dynamic> data = jsonDecode(utf8.decode(response.bodyBytes));
      return data.map((json) => Contact.fromJson(json)).toList();
    } else {
      throw Exception('Failed to load contacts');
    }
  }

  Future<List<Contact>> fetchAllUsers() async {
    final token = await _apiService.getAccessToken();
    if (token == null) {
      throw Exception('No access token');
    }

    final response = await _client.get(
      Uri.parse('${AppConstants.baseUrl}/users/all'),
      headers: {
        'Authorization': 'Bearer $token',
        'Content-Type': 'application/json',
      },
    );

    if (response.statusCode == 200) {
      final List<dynamic> data = jsonDecode(utf8.decode(response.bodyBytes));
      return data.map((json) => Contact.fromJson(json)).toList();
    } else {
      throw Exception('Failed to load contacts');
    }
  }

  Future<Contact> fetchContactById(int userId) async {
    final token = await _apiService.getAccessToken();
    final response = await _client.get(
      Uri.parse('${AppConstants.baseUrl}/users/$userId'),
      headers: {
        'Authorization': 'Bearer $token',
        'Content-Type': 'application/json',
      },
    );

    if (response.statusCode == 200) {
      final data = jsonDecode(utf8.decode(response.bodyBytes));
      return Contact.fromJson(data);
    } else {
      throw Exception('Не удалось загрузить данные контакта');
    }
  }
}
