package cokr.xit.ens.modules.common.ctgy.intgrnbill.support.service.process.template;

import cokr.xit.ens.core.exception.EnsException;
import cokr.xit.ens.core.exception.code.EnsErrCd;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.support.service.process.Pay;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.support.service.process.PayHelperService;
import lombok.Builder;

public class PayHelper<D, PARAM, RSLT> implements Pay<RSLT> {

    private final PARAM param;
    private final PayHelperService<D, PARAM, RSLT> payHelperService;
    private D data;
    private RSLT result;
    private EnsException e;

    @Builder
    PayHelper(PARAM param, PayHelperService payHelperService) {
        this.param = param;
        this.payHelperService = payHelperService;
    }

    @Override
    public void exec() {
        try {
            
            this.data = payHelperService.getData(param);
            
            payHelperService.validate(param, data);
           
            payHelperService.callApi(param, data);
            
            this.result = payHelperService.generateResult(param, data, null);

        } catch (EnsException e) {
            this.e = e;
            this.result = payHelperService.generateResult(param, data, this.e);
        } catch (Exception e) {
            this.e = new EnsException(EnsErrCd.ERR999, "정의되지 않은 오류 입니다", e);
            this.result = payHelperService.generateResult(param, data, this.e);
        } finally {
            payHelperService.saveHist(param, data, e);
        }

    }

    @Override
    public RSLT getResult() {
        return this.result;
    }

    @Override
    public EnsException getException() {
        return this.e;
    }
}
