import 'package:cargocalculaterapp/core/local_source/local_source.dart';
import 'package:cargocalculaterapp/features/profile/data/data_source/remote/profile_remote_data_source.dart';
import 'package:cargocalculaterapp/features/profile/data/models/delete_account_response.dart';
import 'package:cargocalculaterapp/features/profile/data/models/profile_response.dart';
import 'package:cargocalculaterapp/features/profile/data/models/profile_update_request.dart';
import 'package:dio/dio.dart';

import '../../../../../constants/constants.dart';
import '../../../../../core/error/exceptions.dart';
import '../../../../../injector_container.dart';

class ProfileRemoteDataSourceImpl extends ProfileRemoteDataSource {
  final Dio dio;

  ProfileRemoteDataSourceImpl(this.dio);

  @override
  Future<ProfileResponse> getProfile() async {
    try {
      final Response response = await dio.get(
        Constants.baseUrl + Urls.getProfile,
        options: DioConstants.options
          ..headers = {
            "Authorization": "Bearer ${sl<LocalSource>().getAccessToken()}",
          },
      );
      if (response.statusCode == 200 || response.statusCode == 201) {
        return ProfileResponse.fromJson(response.data);
      }
      throw ServerException.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException.fromJson(e.response?.data);
    } on FormatException {
      throw ServerException(message: Validations.someThingWentWrong);
    }
  }

  @override
  Future<ProfileResponse> updateProfile(ProfileUpdateRequest request) async {
    try {
      final Response response = await dio.put(
        Constants.baseUrl + Urls.updateProfile,
        options: DioConstants.options
          ..headers = {
            "Authorization": "Bearer ${sl<LocalSource>().getAccessToken()}",
          },
        data: request,
      );
      if (response.statusCode == 200 || response.statusCode == 201) {
        return ProfileResponse.fromJson(response.data);
      }
      throw ServerException.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException.fromJson(e.response?.data);
    } on FormatException {
      throw ServerException(message: Validations.someThingWentWrong);
    }
  }

  @override
  Future<DeleteAccountResponse> deleteProfile() async {
    try {
      final Response response = await dio.delete(
        Constants.baseUrl + Urls.delete,
        options: DioConstants.options
          ..headers = {
            "Authorization": "Bearer ${sl<LocalSource>().getAccessToken()}",
          },
      );
      if (response.statusCode == 200 || response.statusCode == 201) {
        return DeleteAccountResponse.fromJson(response.data);
      }
      throw ServerException.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException.fromJson(e.response?.data);
    } on FormatException {
      throw ServerException(message: Validations.someThingWentWrong);
    }
  }
}
