package service

import (
	"testing"
	"time"

	"github.com/stretchr/testify/require"
	"github.com/tidbcloud/serverless-service/internal/domain/constant"
)

func TestVerifyParentTimestamp(t *testing.T) {
	end := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)
	parentCreatedAt := end.Add(-24 * time.Hour)
	retention := uint64(7)

	t.Run("nil stays nil (unspecified means latest)", func(t *testing.T) {
		ts, err := verifyParentTimestamp(nil, parentCreatedAt, retention, end)
		require.NoError(t, err)
		require.Nil(t, ts)
	})

	t.Run("explicit timestamp passes through", func(t *testing.T) {
		explicit := end.Add(-time.Hour)
		ts, err := verifyParentTimestamp(&explicit, parentCreatedAt, retention, end)
		require.NoError(t, err)
		require.Equal(t, explicit, *ts)
	})

	t.Run("future timestamp rejected", func(t *testing.T) {
		future := end.Add(time.Minute)
		_, err := verifyParentTimestamp(&future, parentCreatedAt, retention, end)
		require.ErrorContains(t, err, "later than current time")
	})

	t.Run("beyond retention rejected", func(t *testing.T) {
		early := end.Add(-8 * 24 * time.Hour)
		_, err := verifyParentTimestamp(&early, parentCreatedAt, retention, end)
		require.ErrorContains(t, err, "preserve")
	})

	t.Run("before parent creation rejected", func(t *testing.T) {
		early := parentCreatedAt.Add(-time.Hour)
		_, err := verifyParentTimestamp(&early, parentCreatedAt, retention, end)
		require.ErrorContains(t, err, "earlier than parent creation time")
	})
}

func TestSetParentTimestampAnnotation(t *testing.T) {
	annotations := map[string]string{}

	setParentTimestampAnnotation(annotations, nil)
	require.NotContains(t, annotations, constant.ParentTimestampAnnKey)

	ts := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)
	setParentTimestampAnnotation(annotations, &ts)
	require.Equal(t, "2026-09-01T00:00:00Z", annotations[constant.ParentTimestampAnnKey])
}

func TestParentTimestampOrDefault(t *testing.T) {
	now := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)
	explicit := now.Add(-time.Hour)

	t.Run("explicit timestamp passes through", func(t *testing.T) {
		in := explicit
		require.Equal(t, &explicit, parentTimestampOrDefault(&in, []string{"k8s-a"}, "k8s-b", now))
	})

	t.Run("nil stays nil on allowlisted kubernetes", func(t *testing.T) {
		require.Nil(t, parentTimestampOrDefault(nil, []string{"k8s-a"}, "k8s-a", now))
	})

	t.Run("nil defaults to now on unlisted kubernetes", func(t *testing.T) {
		require.Equal(t, &now, parentTimestampOrDefault(nil, []string{"k8s-a"}, "k8s-b", now))
	})

	t.Run("nil defaults to now on empty allowlist", func(t *testing.T) {
		require.Equal(t, &now, parentTimestampOrDefault(nil, nil, "k8s-a", now))
	})
}
