package schedule

import (
	"context"
	"time"
)

func NextMonthlyTaskTimestamp(ctx context.Context, checkpoint int64, start int64) int64 {
	if checkpoint+start == 0 {
		return firstTimestampOfNextMonth(ctx, time.Now().Unix())
	}

	if start > checkpoint {
		return firstTimestampOfNextMonth(ctx, start)
	} else {
		return firstTimestampOfNextMonth(ctx, checkpoint+1)
	}
}

func firstTimestampOfNextMonth(ctx context.Context, now int64) int64 {
	utcTime := time.Unix(now, 0).UTC()
	if utcTime.Day() == 1 && utcTime.Hour()+utcTime.Minute()+utcTime.Second() == 0 {
		return now
	}

	loc, _ := time.LoadLocation("UTC")
	return time.Date(utcTime.Year(), utcTime.Month()+1, 1, 0, 0, 0, 0, loc).Unix()
}
