import 'dart:convert';
import '../constants/api_constants.dart';
import 'http_service.dart';
import 'auth_service.dart';

class UserService {
  static Future<Map<String, dynamic>> getCurrentUser({
    bool forceRefresh = false,
  }) async {
    if (!forceRefresh) {
      final cachedData = await AuthService.getCachedUserData();
      if (cachedData != null) {
        return {'success': true, 'data': cachedData};
      }
    }

    try {
      final response = await HttpService.get(ApiConstants.getUserEndpoint);

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        await AuthService.saveUserData(data);
        return {'success': true, 'data': data};
      } else if (response.statusCode == 401) {
        return {
          'success': false,
          'message': 'Session expired. Please login again.',
        };
      } else if (response.statusCode == 403) {
        return {
          'success': false,
          'message': 'Access denied. Invalid credentials.',
        };
      } else {
        return {
          'success': false,
          'message': 'Server error (${response.statusCode})',
        };
      }
    } catch (e) {
      print('Error fetching user: $e');
      return {
        'success': false,
        'message': 'Network error. Please check your connection.',
      };
    }
  }

  static Future<Map<String, dynamic>> updateFCMToken(String fcmToken) async {
    try {
      final response = await HttpService.post(ApiConstants.updateUserEndpoint, {
        'fcmToken': fcmToken,
      });

      if (response.statusCode == 200) {
        return {'success': true};
      } else if (response.statusCode == 401) {
        return {
          'success': false,
          'message': 'Session expired. Please login again.',
        };
      } else if (response.statusCode == 403) {
        return {
          'success': false,
          'message': 'Access denied. Invalid credentials.',
        };
      } else {
        return {
          'success': false,
          'message': 'Server error (${response.statusCode})',
        };
      }
    } catch (e) {
      print('Error updating FCM token: $e');
      return {
        'success': false,
        'message': 'Network error. Please check your connection.',
      };
    }
  }

  static Future<Map<String, dynamic>> createUser({
    required String email,
    required String password,
    required String displayName,
  }) async {
    try {
      final response = await HttpService.post('/admin/createUser', {
        'email': email,
        'password': password,
        'displayName': displayName,
      });

      final responseData = jsonDecode(response.body);

      if (response.statusCode == 200 || response.statusCode == 201) {
        return {
          'success': responseData['status'] ?? false,
          'message': responseData['message'] ?? 'User created successfully',
          'data': responseData['data'],
        };
      } else {
        return {
          'success': false,
          'message': responseData['message'] ?? 'Failed to create user',
        };
      }
    } catch (e) {
      print('Error creating user: $e');
      return {
        'success': false,
        'message': 'Network error. Please check your connection.',
      };
    }
  }
}
