// Copyright 2019 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.schema.tmch;

import static com.google.common.base.Preconditions.checkState;
import static google.registry.util.DateTimeUtils.toJodaDateTime;
import static google.registry.util.DateTimeUtils.toZonedDateTime;

import google.registry.model.CreateAutoTimestamp;
import google.registry.model.ImmutableObject;
import java.time.ZonedDateTime;
import java.util.Map;
import java.util.Optional;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapKeyColumn;
import javax.persistence.Table;
import org.joda.time.DateTime;

/**
 * A list of TMCH claims labels and their associated claims keys.
 *
 * <p>Note that the primary key of this entity is {@link #revisionId}, which is auto-generated by
 * the database. So, if a retry of insertion happens after the previous attempt unexpectedly
 * succeeds, we will end up with having two exact same claims list with only different {@link
 * #revisionId}. However, this is not an actual problem because we only use the claims list with
 * highest {@link #revisionId}.
 */
@Entity
@Table
public class ClaimsList extends ImmutableObject {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column
  private Long revisionId;

  @Column(nullable = false)
  private CreateAutoTimestamp creationTimestamp = CreateAutoTimestamp.create(null);

  @Column(nullable = false)
  private ZonedDateTime tmdbGenerationTime;

  @ElementCollection
  @CollectionTable(
      name = "ClaimsEntry",
      joinColumns = @JoinColumn(name = "revisionId", referencedColumnName = "revisionId"))
  @MapKeyColumn(name = "domainLabel", nullable = false)
  @Column(name = "claimKey", nullable = false)
  private Map<String, String> labelsToKeys;

  private ClaimsList(ZonedDateTime tmdbGenerationTime, Map<String, String> labelsToKeys) {
    this.tmdbGenerationTime = tmdbGenerationTime;
    this.labelsToKeys = labelsToKeys;
  }

  // Hibernate requires this default constructor.
  private ClaimsList() {}

  /** Constructs a {@link ClaimsList} object. */
  public static ClaimsList create(DateTime creationTimestamp, Map<String, String> labelsToKeys) {
    return new ClaimsList(toZonedDateTime(creationTimestamp), labelsToKeys);
  }

  /** Returns the revision id of this claims list, or throws exception if it is null. */
  public Long getRevisionId() {
    checkState(
        revisionId != null, "revisionId is null because it is not persisted in the database");
    return revisionId;
  }

  /** Returns the TMDB generation time of this claims list. */
  public DateTime getTmdbGenerationTime() {
    return toJodaDateTime(tmdbGenerationTime);
  }

  /** Returns the creation time of this claims list. */
  public DateTime getCreationTimestamp() {
    return creationTimestamp.getTimestamp();
  }

  /** Returns an {@link Map} mapping domain label to its lookup key. */
  public Map<String, String> getLabelsToKeys() {
    return labelsToKeys;
  }

  /** Returns the claim key for a given domain if there is one, empty otherwise. */
  public Optional<String> getClaimKey(String label) {
    return Optional.ofNullable(labelsToKeys.get(label));
  }
}
