package action

import (
	"errors"
	"time"

	"github.com/tidbcloud/fastflow/pkg/entity/run"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"

	"github.com/tidbcloud/tidb-management-service/utilities/workflow"
)

const (
	WaitScheduledTime = "wait_scheduled_time"
)

type WaitScheduledTimeAction struct {
}

func NewWaitScheduledTimeAction() *WaitScheduledTimeAction {
	return &WaitScheduledTimeAction{}
}

func (a *WaitScheduledTimeAction) Name() string {
	return WaitScheduledTime
}

func (a *WaitScheduledTimeAction) Run(ctx run.ExecuteContext, params any) error {
	cctx, span := workflow.GenerateContext(ctx)

	s, ok := ctx.GetVar(workflow.KeyScheduledTime)

	tilog.Info(cctx, "wait scheduled time", zap.String("scheduled_time", s))
	defer func() {
		tilog.Info(cctx, "end wait scheduled time", zap.String("scheduled_time", s))
		span.End()
	}()

	// no scheduled time, skip
	if !ok || s == "" {
		return nil
	}

	scheduledTime, err := time.Parse(time.RFC3339, s)
	if err != nil {
		tilog.Error(cctx, "failed to parse scheduled time", zap.Error(err))
		return err
	}

	if time.Now().Before(scheduledTime) {
		tilog.Info(cctx, "wait scheduled time", zap.String("scheduled_time", s))

		// wait scheduled time
		// action timeout is 60s, so wait 30s
		time.Sleep(30 * time.Second)

		return errors.New("wait scheduled time")
	}
	return nil
}
