// Copyright 2017 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.tools;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static google.registry.pricing.PricingEngineProxy.getPricesForDomainName;

import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import google.registry.model.domain.DomainAuthInfo;
import google.registry.model.domain.DomainCommand;
import google.registry.model.domain.Period;
import google.registry.model.eppcommon.AuthInfo.PasswordAuth;
import google.registry.model.eppinput.EppExtensions;
import google.registry.model.eppinput.EppInput;
import google.registry.model.pricing.PremiumPricingEngine.DomainPrices;
import google.registry.util.StringGenerator;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import java.math.BigDecimal;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;

/** A command to create a new domain via EPP. */
@Parameters(separators = " =", commandDescription = "Create a new domain via EPP.")
final class CreateDomainCommand extends CreateOrUpdateDomainCommand {

  @Parameter(
      names = "--period",
      description = "Initial registration period, in years.")
  private int period = 1;

  @Parameter(
      names = "--force_premiums",
      description = "Force the creation of premium domains.")
  private boolean forcePremiums;

  @Parameter(
      names = "--allocation_token",
      description = "Allocation token to use when creating the domain(s)")
  private String allocationToken;

  @Inject
  @Named("base64StringGenerator")
  StringGenerator passwordGenerator;

  private static final int PASSWORD_LENGTH = 16;

  @Override
  protected void initMutatingEppToolCommand() {
    if (isNullOrEmpty(password)) {
      password = passwordGenerator.createString(PASSWORD_LENGTH);
    }

    for (String domain : domains) {
      CurrencyUnit currency = null;
      BigDecimal cost = null;
      DomainPrices prices = getPricesForDomainName(domain, clock.now());

      // Check if the domain is premium and set the fee on the create command if so.
      if (prices.isPremium()) {
        checkArgument(
            !force || forcePremiums,
            "Forced creates on premium domain(s) require --force_premiums");
        Money createCost = prices.getCreateCost();
        currency = createCost.getCurrencyUnit();
        cost = createCost.multipliedBy(period).getAmount();
        printStream.printf(
            "NOTE: %s is premium at %s per year; sending total cost for %d year(s) of %s %s.\n",
            domain, createCost, period, currency, cost);
      }

      DomainCommand.Create.Builder createBuilder =
          new DomainCommand.Create.Builder()
              .setDomainName(domain)
              .setAuthInfo(DomainAuthInfo.create(PasswordAuth.create(password)))
              .setPeriod(Period.create(period, Period.Unit.YEARS))
              .setNameserverHostNames(ImmutableSortedSet.copyOf(nameservers));

      addEppInput(
          clientId,
          EppInput.create(
                  EppInput.Create.create(createBuilder.build()),
                  EppExtensions.feeCreate(currency, cost),
                  EppExtensions.secDnsCreate(
                      dsRecords.stream()
                          .map(DsRecord::toDsData)
                          .collect(ImmutableSet.toImmutableSet())),
                  EppExtensions.toolMetadata(reason, requestedByRegistrar),
                  EppExtensions.allocationToken(allocationToken))
              .withClTrid("RegistryTool"));
    }
  }
}
