package consts

import (
	"context"
	"strconv"

	"sigs.k8s.io/controller-runtime/pkg/log"

	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
)

const (
	DefaultPodTerminationGracePeriodSeconds = 30

	// This assume after gracefulStopWaitSeconds tidb will stop writing the audit file.
	// and we will rotate the current writing file ourself and push it.
	// tidb will force closing all connection after 15s(time1).
	// ref https://github.com/pingcap/tidb/blob/master/server/server.go#L718
	//
	// the default terminationGracePeriodSeconds of pod is 30s(time2), so that we have at most 15s(time2-time1)
	// to push the log file.
	//
	// the max size of audit log file is 30M so in normal it will enough for us to push the file.
	// one test for reference:
	// [name=/var/log/auditlog/tidb-audit-2022-02-07T13-09-09.222.log] [size=104857600] [takes=6.447067187s]]]
	// manual generate a 100M file and it take 6 second to push it.
	//
	// We set the default value to 12s(time3). The time3 meets the requirement: time3 < (time2 - time1).
	maxPushLogsSeconds = 12
)

func GetAuditLogSidecarGracefulStopWaitSeconds(ctx context.Context, cluster *cloudv1.Cluster, tidbTerminationGracePeriodSeconds int) int {
	logger := log.FromContext(ctx)
	if tidbTerminationGracePeriodSeconds == 0 {
		tidbTerminationGracePeriodSeconds = DefaultPodTerminationGracePeriodSeconds
	}

	out := tidbTerminationGracePeriodSeconds - maxPushLogsSeconds
	if val := cluster.Annotations[AnnoKeyOverrideAuditLogSidecarGracefulStopWaitSeconds]; val != "" {
		logger.Info("use overridden audit log sidecar graceful stop wait seconds", "seconds", val)
		if seconds, err := strconv.ParseInt(val, 10, 64); err == nil {
			out = int(seconds)
		}
	}

	logger.Info("calculated audit log sidecar graceful stop wait seconds", "seconds", out, "tidbTerminationGracePeriodSeconds", tidbTerminationGracePeriodSeconds)
	return out
}
