import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:legacy_shared/src/data/datasource/legacy_shared_remote_datasource.dart';
import 'package:legacy_shared/src/data/models/entities/user_entity.dart';
import 'package:legacy_shared/src/data/models/get_logged_user_response_model.dart';
import 'package:sf_infrastructure/sf_infrastructure.dart';

class LegacySharedRemoteDatasourceImpl implements LegacySharedRemoteDatasource {
  LegacySharedRemoteDatasourceImpl(this._repository);

  final QuestiaRepository _repository;

  @override
  Future<UserEntity> getLoggedUser({required String token}) async {
    try {
      /*final response = await _repository.get<Map<String, dynamic>>(
        '/users/api/auth/me',
      );
      final data = response.data!['item'];
      if (data == null || data.isEmpty) {
        throw Exception('Empty response from /auth/me');
      }

      final model = GetLoggedUserResponseModel.fromJson(data);*/
      final model = GetLoggedUserResponseModel(item:
      GetLoggedUserItemResponseModel(
          id: '1111',
          firstName: 'Juan',
          email: 'juan@test.com',
          phone: '111111111'));
      return model.toEntity();
    } on DioException catch (error) {
      throw _mapDioError(
        error,
        defaultMessage: error.message ?? 'Error getting logged user',
      );
    }
  }
}

Exception _mapDioError(DioException error, {required String defaultMessage}) {
  final apiMsg = _extractApiMessage(error.response?.data);
  final msg = apiMsg ?? error.message ?? defaultMessage;
  return Exception(msg);
}

String? _extractApiMessage(Object? data) {
  if (data == null) return null;

  if (data is Map) {
    final errorObj = data['error'];
    if (errorObj is Map && errorObj['message'] is String) {
      return (errorObj['message'] as String).trim();
    }
    if (data['message'] is String) {
      return (data['message'] as String).trim();
    }
    return null;
  }

  if (data is String) {
    final raw = data.trim();
    if (raw.isEmpty) return null;

    try {
      final decoded = jsonDecode(raw);
      return _extractApiMessage(decoded);
    } catch (_) {
      return raw;
    }
  }

  return null;
}
