import 'package:dio/dio.dart';
import 'package:qadirneyriz/config/config.dart';
import 'package:qadirneyriz/setting/setting.dart';
import 'package:qadirneyriz/utils/result/result.dart';

class AuthServices {
  Future<Result?> loginApi(
      {required String mobile, String? password, String? otp}) async {
    assert(password != null || otp != null);
    try {
      Map<String, String> headers = {"Accept": "application/json"};
      FormData? formData;
      formData = password != null
          ? FormData.fromMap({"mobile": mobile, "password": password})
          : FormData.fromMap({"mobile": mobile, "otp": otp});

      final res = await Dio().post("${config.network.baseUrl}login",
          data: formData, options: Options(headers: headers));

      if (res.statusCode == 200 || res.statusCode == 201) {
        setting.userLocalDb.saveUserField('token', res.data['token']);
        setting.userLocalDb.saveUserField('mobile', res.data['mobile']);
        setting.userLocalDb.saveUserField('name', res.data['name']);
        setting.userLocalDb.saveUserField('role', res.data['role']);
        setting.userLocalDb.saveUserField('access', res.data['access']);
        return Result(isOk: true, message: res.data['msg']);
      }
    } on DioException catch (e) {
      return Result(
          isOk: false,
          errors: e.response!.data['errors'],
          message: e.response!.data['msg']);
    }
    return const Result(isOk: false);
  }

  Future<Result?> sendOtpApi({required String mobile}) async {
    try {
      Map<String, String> headers = {"Accept": "application/json"};
      FormData? formData;
      formData = FormData.fromMap({"mobile": mobile});

      final res = await Dio().post("${config.network.baseUrl}sendOtp",
          data: formData, options: Options(headers: headers));

      if (res.statusCode == 200 || res.statusCode == 201) {
        return Result(isOk: true, message: res.data['msg']);
      }
    } on DioException catch (e) {
      return Result(
          isOk: false,
          errors: e.response!.data['errors'],
          message: e.response!.data['msg']);
    }
    return const Result(isOk: false);
  }
}
