// Copyright 2020 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.beam.common;

import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.immutableObjectCorrespondence;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.loadAllOf;
import static google.registry.testing.DatabaseHelper.newHost;

import com.google.common.collect.ImmutableList;
import google.registry.beam.TestPipelineExtension;
import google.registry.model.host.Host;
import google.registry.persistence.transaction.JpaTestExtensions;
import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension;
import google.registry.persistence.transaction.JpaTransactionManagerExtension;
import google.registry.testing.FakeClock;
import java.io.Serializable;
import java.time.Instant;
import org.apache.beam.sdk.transforms.Create;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

/** Unit test for {@link RegistryJpaIO.Write}. */
class RegistryJpaWriteTest implements Serializable {

  private final FakeClock fakeClock = new FakeClock(Instant.parse("2000-01-01T00:00:00.0Z"));

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

  @RegisterExtension
  final transient TestPipelineExtension testPipeline =
      TestPipelineExtension.create().enableAbandonedNodeEnforcement(true);

  @Test
  void writeToSql_twoWriters() {
    tm().transact(() -> tm().put(JpaTransactionManagerExtension.makeRegistrar2()));
    ImmutableList.Builder<Host> hostsBuilder = new ImmutableList.Builder<>();
    for (int i = 0; i < 3; i++) {
      hostsBuilder.add(newHost(String.format("ns%d.example.tld", i)));
    }
    ImmutableList<Host> hosts = hostsBuilder.build();
    testPipeline
        .apply(Create.of(hosts))
        .apply(RegistryJpaIO.<Host>write().withName("Host").withBatchSize(4));
    testPipeline.run().waitUntilFinish();

    assertThat(loadAllOf(Host.class))
        .comparingElementsUsing(immutableObjectCorrespondence("revisions", "updateTimestamp"))
        .containsExactlyElementsIn(hosts);
  }
}
