package schedule

import (
	"context"
	"time"

	log "github.com/sirupsen/logrus"
	"github.com/tidbcloud/observability/o11ymetering/pkg/common/config"
	"github.com/tidbcloud/observability/o11ymetering/pkg/common/message"
	"github.com/tidbcloud/observability/o11ymetering/pkg/service/statistic"
)

func MonthlyProportionSumGlobally() {
	go func() {
		ticker := time.NewTicker(1 * time.Hour)
		err := tryToGenerateMonthlyProportionSum(context.Background())
		if err != nil {
			log.Errorf(err.Error())
		}

		for range ticker.C {
			err := tryToGenerateMonthlyProportionSum(context.Background())
			if err != nil {
				log.Errorf(err.Error())
			}
		}
	}()
}

func tryToGenerateMonthlyProportionSum(ctx context.Context) error {
	t := time.Now()

	isFourthDayMidnight := t.Day() == 4 && t.Hour() == 0
	if (isFourthDayMidnight && config.GetScheduleConfig().MonthlyProportion) ||
		(config.GetScheduleConfig().RenewMonthlyProportionTs > 0 && t.Unix() > int64(config.GetScheduleConfig().RenewMonthlyProportionTs)) {
		currentMonthFirstDay := time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC)

		previousMonthFirstDay := currentMonthFirstDay.AddDate(0, -1, 0)
		previousMonthFirstDay = time.Date(previousMonthFirstDay.Year(), previousMonthFirstDay.Month(), 1, 0, 0, 0, 0, time.UTC)

		log.Infof("start to generate monthly proportion report")
		resp, err := statistic.CalculateMonthlyProportionSum(ctx, message.MonthlyProportionSumReq{
			// nolint:gosec
			Timestamp: int32(previousMonthFirstDay.Unix()),
		})
		if err != nil {
			log.Errorf("CalculateMonthlyProportionSum failed, err = %s", err.Error())
			return err
		}
		log.Infof("generate monthly proportion sum report succeed, upload file to %s", resp.File)
	}

	return nil
}
