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/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, AuthDto>> login({
    required String email,
    required String password,
    required String deviceId,
    required String deviceName,
    required String deviceType,
    required String platform,
    required String osVersion,
    required String appVersion,
    String? fcmToken,
  }) async {
    try {
      final response = await _apiClient.post(
        ApiPath.login,
        data: {
          'email': email,
          'password': password,
          'device_id': deviceId,
          'device_name': deviceName,
          'device_type': deviceType,
          'platform': platform,
          'os_version': osVersion,
          'app_version': appVersion,
          if (fcmToken != null) 'fcm_token': fcmToken,
        },
      );

      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, headers: getAuthorizationHeader());
      return DC.data(unit);
    } on ApiFailure catch (e, s) {
      log('login', name: _logName, error: e, stackTrace: s);
      return DC.error(AuthFailure.serverError(e));
    }
  }
}
