package cron

import (
	"context"
	"math/rand"
	"time"

	"github.com/aws/aws-lambda-go/lambdacontext"
	"gitlab.com/uafrica/go-utils/errors"
	"gitlab.com/uafrica/go-utils/service"
)

type LambdaCronHandler func(lambdaCtx context.Context) error

func (cron Cron) Handler(lambdaCtx context.Context) error {
	lc, _ := lambdacontext.FromContext(lambdaCtx)
	requestID := lc.AwsRequestID

	cronName, cronFunc := cron.router.Route(lc.InvokedFunctionArn)
	if cronFunc == nil {
		return errors.Errorf("request-id:%s unknown cron function(%s)", lc.InvokedFunctionArn)
	}

	//got a handler, prepare to run:
	rand.Seed(time.Now().Unix())

	ctx := Context{
		Context: service.NewContext(lambdaCtx, map[string]interface{}{
			"env":        cron.env,
			"request-id": requestID,
			"cron":       cronName,
		}),
		Name: cronName,
	}

	//report handler crashes
	defer cron.crashReporter.Catch(ctx)

	//todo: set log level, trigger log on conditions, sync at end of transaction - after log level was determined
	ctx.Infof("Start CRON Handler")

	if err := cronFunc(ctx); err != nil {
		return errors.Wrapf(err, "Cron(%s) failed", cronName)
	}
	return nil
}