package ru.soune.nocopy.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import ru.soune.nocopy.dto.BaseRequest;
import ru.soune.nocopy.dto.BaseResponse;
import ru.soune.nocopy.dto.MessageCode;
import ru.soune.nocopy.dto.payment.PaymentRequest;
import ru.soune.nocopy.dto.payment.PaymentResponse;
import ru.soune.nocopy.entity.payment.Payment;
import ru.soune.nocopy.exception.PaymentNotFoundException;
import ru.soune.nocopy.service.payment.PaymentService;

import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class PaymentHandler implements RequestHandler{

    private final PaymentService paymentService;

    private final ObjectMapper objectMapper;

    @Override
    public BaseResponse handle(BaseRequest request) throws Exception {
        PaymentRequest paymentRequest = objectMapper.convertValue(request.getMessageBody(), PaymentRequest.class);
        String action = paymentRequest.getAction();

        switch (action) {
            case "user_payments":
                List<Payment> payments = paymentService.userPayments(paymentRequest.getEmail());

                return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(),
                        MessageCode.SUCCESS.getDescription(), new PaymentResponse(payments));
            case "payment_info":
                try {
                    Payment payment = paymentService.paymentInfo(paymentRequest.getPaymentUuid());
                    return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(),
                            MessageCode.SUCCESS.getDescription(), new PaymentResponse(List.of(payment)));
                } catch (PaymentNotFoundException e) {
                    return new BaseResponse(request.getMsgId(), MessageCode.PAYMENT_NOT_FOUND.getCode(),
                            MessageCode.PAYMENT_NOT_FOUND.getDescription(), Map.of("paymentUuid",
                            paymentRequest.getPaymentUuid()));
                }
        }

        return null;
    }
}
