import 'dart:developer';

import 'package:dartz/dartz.dart';
import 'package:data_channel/data_channel.dart';
import 'package:injectable/injectable.dart';

import '../../../common/api/api_client.dart';
import '../../../common/api/api_failure.dart';
import '../../../common/function/app_function.dart';
import '../../../common/url/api_path.dart';
import '../../../domain/user/user.dart';
import '../user_dtos.dart';

@injectable
class UserRemoteDataProvider {
  final ApiClient _apiClient;

  static const _logName = 'UserRemoteDataProvider';

  UserRemoteDataProvider(this._apiClient);

  Future<DC<UserFailure, UserDto>> updateUser({
    required String name,
    required String userId,
  }) async {
    try {
      final response = await _apiClient.put(
        '${ApiPath.user}/$userId',
        data: {'name': name, 'is_active': true},
        headers: getAuthorizationHeader(),
      );

      if (response.statusCode == 400) {
        return DC.error(UserFailure.unexpectedError());
      }

      if (response.statusCode != 200) {
        return DC.error(
          UserFailure.dynamicErrorMessage(response.data['message']),
        );
      }

      final dto = UserDto.fromJson(response.data);

      return DC.data(dto);
    } on ApiFailure catch (e, s) {
      log('updateUser', name: _logName, error: e, stackTrace: s);
      return DC.error(UserFailure.serverError(e));
    }
  }

  Future<DC<UserFailure, Unit>> changePassword({
    required String newPassword,
    required String currentPassword,
    required String userId,
  }) async {
    try {
      final response = await _apiClient.put(
        '${ApiPath.user}/$userId/password',
        data: {
          'new_password': newPassword,
          'current_password': currentPassword,
        },
        headers: getAuthorizationHeader(),
      );

      if (response.statusCode == 400) {
        return DC.error(UserFailure.unexpectedError());
      }

      if (response.statusCode != 200) {
        return DC.error(
          UserFailure.dynamicErrorMessage(response.data['error']),
        );
      }

      return DC.data(unit);
    } on ApiFailure catch (e, s) {
      log('changePassword', name: _logName, error: e, stackTrace: s);
      return DC.error(UserFailure.serverError(e));
    }
  }
}
