// ignore_for_file: collection_methods_unrelated_type
import 'dart:developer';
import 'package:dio/dio.dart';

class Limit {
  final double dailyLimit;
  final double usedLimit;

  Limit({
    required this.dailyLimit,
    required this.usedLimit,
  });

  factory Limit.fromJson(Map<String, dynamic> json) {
    return Limit(
      dailyLimit: (json['dailyLimit'] as num).toDouble(),
      usedLimit: (json['usedLimit'] as num).toDouble(),
    );
  }
}

class LimitService {
  final Dio _dio;
  LimitService(this._dio);

  Future<Limit> getLimit() async {
    try {
      final response = await _dio.get('/api/customer/daily-limit');
      if (response.statusCode == 200) {
        log('Response: ${response.data}');
        return Limit.fromJson(response.data);
      } else {
        throw Exception('Failed to load');
      }
    } on DioException catch (e) {
      throw Exception('Network error: ${e.message}');
    } catch (e) {
      throw Exception('Unexpected error: ${e.toString()}');
    }
  }

  void editLimit(double newLimit) async {
    try {
      final response = await _dio.post('/api/customer/daily-limit',
          data: '{"amount": $newLimit}');
      if (response.statusCode == 200) {
        log('Response: ${response.data}');
      } else {
        throw Exception('Failed to load');
      }
    } on DioException catch (e) {
      throw Exception('Network error: ${e.message}');
    } catch (e) {
      throw Exception('Unexpected error: ${e.toString()}');
    }
  }

  Future getOtpTLimit({
    required String mobileNumber,
  }) async {
    final response = await _dio.post(
      '/api/otp/send',
      data: {'mobileNumber': mobileNumber, 'type': "TLIMIT"},
    );
    if (response.statusCode != 200) {
      throw Exception("Invalid Mobile Number/Type");
    }
    print(response.toString());
    return response.toString();
  }

  Future validateOtp({
    required String otp,
    required String mobileNumber,
  }) async {
    final response = await _dio.post(
      '/api/otp/verify?mobileNumber=$mobileNumber',
      data: {
        'otp': otp,
      },
    );
    if (response.statusCode != 200) {
      throw Exception("Wrong OTP");
    }
    return response.toString();
  }
}
