import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:inventory_system/services/api_service.dart';
import 'package:inventory_system/services/session_manager.dart';

class UserService {
  Future<List<dynamic>> fetchUsers() async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/UserList');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Fetching users from: $uri");

    final Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.post(uri, headers: headers);

      if (response.statusCode == 200) {
        return response.body.isNotEmpty ? jsonDecode(response.body) : [];
      } else {
        throw Exception('Failed to load users. Status: ${response.statusCode}, Body: ${response.body}');
      }
    } on SocketException {
      throw Exception('No Internet connection.');
    } catch (e) {
      debugPrint('Error fetching users: $e');
      rethrow;
    }
  }

  Future<Map<String, dynamic>> getUserInfo() async {
    final uri = Uri.parse('${ApiService.baseUrl}/IdentityAPI/GetUserInformation');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Fetching user info from: $uri");

    final Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.post(uri, headers: headers);

      if (response.statusCode == 200) {
        return response.body.isNotEmpty ? jsonDecode(response.body) : {};
      } else {
        throw Exception('Failed to load user info. Status: ${response.statusCode}, Body: ${response.body}');
      }
    } on SocketException {
      throw Exception('No Internet connection.');
    } catch (e) {
      debugPrint('Error fetching user info: $e');
      rethrow;
    }
  }

  Future<List<dynamic>> _getMasterStores(int userId) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/StoreSpecificMasterList/$userId');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Fetching master stores for user $userId from: $uri");

    final Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.post(uri, headers: headers);
      if (response.statusCode == 200) {
        return response.body.isNotEmpty ? jsonDecode(response.body) : [];
      } else {
        throw Exception('Failed to get master stores. Status: ${response.statusCode}, Body: ${response.body}');
      }
    } on SocketException {
      throw Exception('No Internet connection.');
    } catch (e) {
      debugPrint('Error fetching master stores: $e');
      rethrow;
    }
  }

  Future<Map<String, dynamic>> isInventoryMaster(String username) async {
    try {
      final users = await fetchUsers();
      final user = users.firstWhere(
        (u) => u['userName']?.toString().toLowerCase() == username.toLowerCase(),
        orElse: () => null,
      );

      if (user == null) {
        return {'isInventoryMaster': false, 'message': 'User not found'};
      }

      final userId = user['id'];
      final masterStores = await _getMasterStores(userId);
      final bool isMaster = masterStores.isNotEmpty;

      return {'isInventoryMaster': isMaster};
    } catch (e) {
      debugPrint('Error in isInventoryMaster check: $e');
      return {'isInventoryMaster': false, 'message': e.toString()};
    }
  }
}
