// Copyright 2026 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package google.registry.cache;

import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatabaseHelper.persistActiveHost;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import google.registry.model.host.Host;
import google.registry.persistence.transaction.JpaTestExtensions;
import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension;
import google.registry.testing.DatabaseHelper;
import google.registry.testing.FakeClock;
import java.time.Duration;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

/** Tests for {@link MultilayerHostCache}. */
public class MultilayerHostCacheTest {

  @RegisterExtension
  final JpaIntegrationTestExtension jpa =
      new JpaTestExtensions.Builder().buildIntegrationTestExtension();

  private final SimplifiedJedisClient jedisClient = mock(SimplifiedJedisClient.class);
  private final FakeClock clock = new FakeClock();
  private final CacheMetrics cacheMetrics = mock(CacheMetrics.class);
  private MultilayerHostCache cache;

  @BeforeEach
  void beforeEach() {
    cache = new MultilayerHostCache(jedisClient, clock, cacheMetrics);
  }

  @Test
  void testLoad_fromDatabase_populatesCaches() {
    Host host = persistActiveHost("ns1.example.tld");
    assertThat(cache.loadByRepoId(host.getRepoId())).hasValue(host);

    // We should have filled the caches after one attempt to load from Valkey
    verify(jedisClient).get(Host.class, host.getRepoId());
    verify(jedisClient).set(new SimplifiedJedisClient.JedisResource<>(host.getRepoId(), host));
    verify(cacheMetrics).recordLookup("Host", CacheMetrics.CacheHitType.MISS);

    // Further loads hit the local cache
    assertThat(cache.loadByRepoId(host.getRepoId())).hasValue(host);
    verify(cacheMetrics).recordLookup("Host", CacheMetrics.CacheHitType.LOCAL);
    verifyNoMoreInteractions(jedisClient);
    verifyNoMoreInteractions(cacheMetrics);
  }

  @Test
  void testLoad_fromValkey() {
    // Note: we don't save the host to SQL
    Host host = DatabaseHelper.newHost("ns1.example.tld");
    // We hit the Valkey cache first
    when(jedisClient.get(Host.class, host.getRepoId())).thenReturn(Optional.of(host));
    assertThat(cache.loadByRepoId(host.getRepoId())).hasValue(host);
    verify(cacheMetrics).recordLookup("Host", CacheMetrics.CacheHitType.REMOTE);
    verifyNoMoreInteractions(cacheMetrics);
  }

  @Test
  void testLoad_missing() {
    assertThat(cache.loadByRepoId("nonexistent")).isEmpty();
    verify(cacheMetrics).recordLookup("Host", CacheMetrics.CacheHitType.MISS_NONEXISTENT);
    verifyNoMoreInteractions(cacheMetrics);
  }

  @Test
  void testLoad_filtersOutDeletedHost() {
    Host host =
        persistActiveHost("ns1.example.tld")
            .asBuilder()
            .setDeletionTime(clock.now().plus(Duration.ofDays(1)))
            .build();
    when(jedisClient.get(Host.class, host.getRepoId())).thenReturn(Optional.of(host));
    assertThat(cache.loadByRepoId(host.getRepoId())).hasValue(host);

    clock.advanceBy(Duration.ofDays(2));
    assertThat(cache.loadByRepoId(host.getRepoId())).isEmpty();
  }
}
