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/auth/auth.dart';
import '../auth_dtos.dart';

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

  AuthRemoteDataProvider(this._apiClient);

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

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

      final dto = LoginDto.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 {
      final response = await _apiClient.post(
        ApiPath.logout,
        headers: getAuthorizationHeader(),
      );

      if (response.data['success'] == false) {
        return DC.error(const AuthFailure.unexpectedError());
      }

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