package runtime

import (
	"context"
	"fmt"
	"time"

	"github.com/tidbcloud/AgentTeam/internal/store/automation"
)

// Eventer owns AgentTeam-native wait resume transitions. Waits do not occupy runner
// leases; they resume durable job runs from external AgentTeam/provider events.
type Eventer struct {
	store *automation.Store
	now   func() time.Time
}

func NewEventer(store *automation.Store, now func() time.Time) *Eventer {
	return &Eventer{store: store, now: now}
}

func (e *Eventer) ResumeWait(ctx context.Context, workspaceID string, waitID string, actorPrincipalID string, resultJSON string) (automation.AutomationWait, error) {
	if e == nil || e.store == nil {
		return automation.AutomationWait{}, fmt.Errorf("automation eventer store is nil")
	}
	now := e.currentTime()
	wait, jobRun, err := e.store.ResolveWait(ctx, workspaceID, waitID, actorPrincipalID, resultJSON, now)
	if err != nil {
		return automation.AutomationWait{}, err
	}
	if _, err := NewScheduler(e.store, e.now).ScheduleRun(ctx, wait.WorkspaceID, wait.RunID); err != nil {
		return automation.AutomationWait{}, err
	}
	if _, err := e.store.CompleteRunIfTerminal(ctx, jobRun.WorkspaceID, jobRun.RunID, now); err != nil {
		return automation.AutomationWait{}, err
	}
	return wait, nil
}

func (e *Eventer) currentTime() time.Time {
	if e.now != nil {
		return e.now()
	}
	return time.Now().UTC()
}
