package engine

import (
	"fmt"
	"time"

	"github.com/exchain/go-exchain/op-node/rollup"
	"github.com/exchain/go-exchain/op-service/eth"
)

type PayloadProcessEvent struct {
	// if payload should be promoted to (local) safe (must also be pending safe, see DerivedFrom)
	Concluding bool
	// payload is promoted to pending-safe if non-zero
	DerivedFrom  eth.L1BlockRef
	BuildStarted time.Time

	Envelope *eth.ExecutionPayloadEnvelope
	Ref      eth.L2BlockRef
}

func (ev PayloadProcessEvent) String() string {
	return "payload-process"
}

func (eq *EngDeriver) onPayloadProcess(ev PayloadProcessEvent) {
	insertStart := time.Now()
	err := eq.ec.engine.ProcessPayload(ev.Envelope.ExecutionPayload.Payload)
	if err != nil {
		eq.emitter.Emit(rollup.EngineTemporaryErrorEvent{
			Err: fmt.Errorf("failed to insert execution payload: %w", err),
		})
		return
	}
	eq.emitter.Emit(PayloadSuccessEvent{
		Concluding:    ev.Concluding,
		DerivedFrom:   ev.DerivedFrom,
		BuildStarted:  ev.BuildStarted,
		InsertStarted: insertStart,
		Envelope:      ev.Envelope,
		Ref:           ev.Ref,
	})
	return
}
