import 'dart:developer';

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

import '../../../common/api/api_client.dart';
import '../../../common/api/api_failure.dart';
import '../../../common/url/api_path.dart';
import '../../../domain/auth/auth.dart';
import '../auth_dtos.dart';

@injectable
class AuthRemoteDataProvider {
  final ApiClient _apiClient;
  final String _logName = "AuthRemoteDataProvider";

  AuthRemoteDataProvider(this._apiClient);

  Future<DC<AuthFailure, AuthDto>> login({
    required String email,
    required String password,
  }) async {
    try {
      final response = await _apiClient.post(
        ApiPath.login,
        data: {'email': email, 'password': password},
      );

      if (response.data['code'] == 401) {
        return DC.error(
          AuthFailure.serverError(
            ApiFailure.unauthorized('Incorrect email or password'),
          ),
        );
      }

      final dto = AuthDto.fromJson(response.data['data']);
      return DC.data(dto);
    } on ApiFailure catch (e, s) {
      log('login', name: _logName, error: e, stackTrace: s);
      return DC.error(AuthFailure.serverError(e));
    }
  }

  Future<DC<AuthFailure, Unit>> logout() async {
    try {
      await _apiClient.post(ApiPath.logout);
      return DC.data(unit);
    } on ApiFailure catch (e, s) {
      log('login', name: _logName, error: e, stackTrace: s);
      return DC.error(AuthFailure.serverError(e));
    }
  }
}
