import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/auth/model/region_model.dart';
import 'package:syncrow_web/pages/auth/model/token.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';
import 'package:syncrow_web/utils/constants/api_const.dart';

class AuthenticationAPI {
  static Future<Token> loginWithEmail({required var model}) async {
    try {
      final response = await HTTPService().post(
          path: ApiEndpoints.login,
          body: model.toJson(),
          showServerMessage: true,
          expectedResponseModel: (json) {
            return Token.fromJson(json['data']);
          });
      return response;
    } on DioException catch (e) {
      final message = e.response?.data['error']['message'] ??
          'An error occurred while logging in';
      throw APIException(message);
    }
  }

  static Future forgetPassword({
    required var email,
    required var password,
    required var otpCode,
  }) async {
    try {
      final response = await HTTPService().post(
          path: ApiEndpoints.forgetPassword,
          body: {"email": email, "password": password, "otpCode": otpCode},
          showServerMessage: true,
          expectedResponseModel: (json) {});
      return response;
    } on DioException catch (e) {
      final message = e.response?.data['error']['message'] ??
          'An error occurred while resetting the password';
      throw APIException(message);
    }
  }

  static Future<int?> sendOtp({required String email}) async {
    final response = await HTTPService().post(
        path: ApiEndpoints.sendOtp,
        body: {"email": email, "type": "PASSWORD"},
        showServerMessage: true,
        expectedResponseModel: (json) {
          return json['data']['cooldown'];
        });
    return response;
  }

  static Future verifyOtp(
      {required String email, required String otpCode}) async {
    try {
      final response = await HTTPService().post(
          path: ApiEndpoints.verifyOtp,
          body: {"email": email, "type": "PASSWORD", "otpCode": otpCode},
          showServerMessage: true,
          expectedResponseModel: (json) {
            if (json['message'] == 'Otp Verified Successfully') {
              return true;
            } else {
              return false;
            }
          });
      return response;
    } on APIException catch (e) {
      throw APIException(e.message);
    } catch (e) {
      throw APIException('An error occurred while verifying the OTP');
    }
  }

  static Future<List<RegionModel>> fetchRegion() async {
    final response = await HTTPService().get(
        path: ApiEndpoints.getRegion,
        showServerMessage: true,
        expectedResponseModel: (json) {
          return (json as List)
              .map((zone) => RegionModel.fromJson(zone))
              .toList();
        });
    return response;
  }
}
