import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_url.dart';
import 'package:niogu_ecommerce_v1/core/errors/exceptions.dart';
import 'package:niogu_ecommerce_v1/core/models/api_response_model.dart';
import 'package:niogu_ecommerce_v1/core/utils/log_message.dart';
import 'package:niogu_ecommerce_v1/features/checkout/data/models/checkout_model.dart';

abstract class ICheckoutRemoteDatasource {
  Future<ApiResponseModel<CheckoutResponse>> checkout(
    OnlineOrderRequest request,
  );
}

class CheckoutRemoteDatasourceImpl implements ICheckoutRemoteDatasource {
  final Dio _dio;

  CheckoutRemoteDatasourceImpl(this._dio);

  @override
  Future<ApiResponseModel<CheckoutResponse>> checkout(
    OnlineOrderRequest request,
  ) async {
    try {
      final formData = FormData.fromMap({
        "data": jsonEncode(request.toJson()),
        "payment_proof_file": request.paymentProofFile,
      });

      final response = await _dio.post(AppUrl.CHECKOUT, data: formData);

      return ApiResponseModel<CheckoutResponse>.fromJson(
        response.data,
        (json) => CheckoutResponse.fromJson(json as Map<String, dynamic>),
      );
    } on DioException catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);

      throw ServerException("Terjadi kesalahan koneksi");
    }
  }
}
