package click.kamil.examples.statemachine.extended.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    @Qualifier("paymentStateMachine")
    private StateMachine<String, String> stateMachine;

    @Autowired
    private StateMachinePersister<String, String, String> persister;

    @Override
    public void processPayment(String paymentId) {
        // Send a trigger mapped strictly to PaymentStateMachineConfig
        stateMachine.sendEvent("AUTHORIZE");
    }

    @Override
    public void capturePayment(String paymentId) {
        try {
            persister.restore(stateMachine, paymentId);
        } catch (Exception e) {}
        
        org.springframework.messaging.Message<String> msg = org.springframework.messaging.support.MessageBuilder
            .withPayload("CAPTURE")
            .setHeader("paymentId", paymentId)
            .build();
        stateMachine.sendEvent(msg);
    }
}
