/*
 * Copyright 2021 Google LLC
 *
 * 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
 *
 *      https://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 com.google.android.apps.exposurenotification.storage;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import com.google.auto.value.AutoValue;
import com.google.auto.value.AutoValue.CopyAnnotations;
import org.threeten.bp.Instant;

/**
 * An entity, which represents a request to a verification server for a verification code as part
 * of the self-reporting flow (i.e. represents a request to /api/user-report).
 */
@AutoValue
@Entity
public abstract class VerificationCodeRequestEntity {

  @CopyAnnotations
  @PrimaryKey(autoGenerate = true)
  public abstract long getId();

  @CopyAnnotations
  @NonNull
  public abstract Instant getRequestTime();

  @CopyAnnotations
  @Nullable
  public abstract Instant getExpiresAtTime();

  @CopyAnnotations
  @NonNull
  public abstract String getNonce();

  public abstract Builder toBuilder();

  public static Builder newBuilder() {
    return new AutoValue_VerificationCodeRequestEntity.Builder()
        // AutoValue complains if fields not marked @Nullable are not set, but primitives cannot be
        // @Nullable, so we set empty here.
        .setId(0L);
  }

  @AutoValue.Builder
  public abstract static class Builder {

    public abstract Builder setId(long id);

    public abstract Builder setRequestTime(Instant requestTime);

    public abstract Builder setExpiresAtTime(Instant expiresAtTime);

    public abstract Builder setNonce(String nonce);

    public abstract VerificationCodeRequestEntity build();
  }

  /**
   * Creates a {@link VerificationCodeRequestEntity}. This is a factory method required by Room.
   * Normally the builder should be used instead.
   *
   * <p>The {@code id} param is required by Room but we ignore it and use zero instead so that the
   * ID will be autogenerated.
   */
  public static VerificationCodeRequestEntity create(
      long id, Instant requestTime, Instant expiresAtTime, String nonce) {
    return newBuilder()
        .setId(0L)
        .setRequestTime(requestTime)
        .setExpiresAtTime(expiresAtTime)
        .setNonce(nonce)
        .build();
  }

}
