// 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.reporting.icann;

import static google.registry.reporting.icann.IcannReportingModule.ICANN_REPORTING_DATA_SET;
import static google.registry.reporting.icann.QueryBuilderUtils.getQueryFromFile;
import static google.registry.reporting.icann.QueryBuilderUtils.getTableName;

import com.google.common.collect.ImmutableMap;
import google.registry.config.RegistryConfig.Config;
import google.registry.util.SqlTemplate;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

/** Utility class that produces SQL queries used to generate activity reports from Bigquery. */
public final class ActivityReportingQueryBuilder implements QueryBuilder {

  // Names for intermediary tables for overall activity reporting query.
  static final String REGISTRAR_OPERATING_STATUS = "registrar_operating_status";
  static final String DNS_COUNTS = "dns_counts";
  static final String MONTHLY_LOGS = "monthly_logs";
  static final String EPP_METRICS = "epp_metrics";
  static final String RDAP_COUNTS = "rdap_counts";
  static final String ACTIVITY_REPORT_AGGREGATION = "activity_report_aggregation";

  private final String projectId;
  private final DnsCountQueryCoordinator dnsCountQueryCoordinator;
  private final String icannReportingDataSet;

  @Inject
  ActivityReportingQueryBuilder(
      @Config("projectId") String projectId,
      @Named(ICANN_REPORTING_DATA_SET) String icannReportingDataSet,
      DnsCountQueryCoordinator dnsCountQueryCoordinator) {
    this.projectId = projectId;
    this.dnsCountQueryCoordinator = dnsCountQueryCoordinator;
    this.icannReportingDataSet = icannReportingDataSet;
  }

  /** Returns the aggregate query which generates the activity report from the saved view. */
  @Override
  public String getReportQuery(YearMonth yearMonth) {
    return String.format(
        "#standardSQL\nSELECT * FROM `%s.%s.%s`",
        projectId, icannReportingDataSet, getTableName(ACTIVITY_REPORT_AGGREGATION, yearMonth));
  }

  /** Sets the month we're doing activity reporting for, and returns the view query map. */
  @Override
  public ImmutableMap<String, String> getViewQueryMap(YearMonth yearMonth) {
    LocalDate firstDayOfMonth = yearMonth.atDay(1);
    // The pattern-matching is inclusive, so we subtract 1 day to only report that month's data.
    LocalDate lastDayOfMonth = yearMonth.atDay(1).plusMonths(1).minusDays(1);

    ImmutableMap.Builder<String, String> queriesBuilder = ImmutableMap.builder();
    String operationalRegistrarsQuery;
    operationalRegistrarsQuery =
        SqlTemplate.create(getQueryFromFile(REGISTRAR_OPERATING_STATUS + ".sql"))
            .put("PROJECT_ID", projectId)
            .build();
    queriesBuilder.put(
        getTableName(REGISTRAR_OPERATING_STATUS, yearMonth), operationalRegistrarsQuery);

    String dnsCountsQuery = dnsCountQueryCoordinator.createQuery();
    queriesBuilder.put(getTableName(DNS_COUNTS, yearMonth), dnsCountsQuery);

    // Convert reportingMonth into YYYYMMDD format for Bigquery table partition pattern-matching.
    DateTimeFormatter logTableFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    String monthlyLogsQuery =
        SqlTemplate.create(getQueryFromFile(MONTHLY_LOGS + ".sql"))
            .put("PROJECT_ID", projectId)
            .put("FIRST_DAY_OF_MONTH", logTableFormatter.format(firstDayOfMonth))
            .put("LAST_DAY_OF_MONTH", logTableFormatter.format(lastDayOfMonth))
            .build();
    queriesBuilder.put(getTableName(MONTHLY_LOGS, yearMonth), monthlyLogsQuery);

    String eppQuery =
        SqlTemplate.create(getQueryFromFile(EPP_METRICS + ".sql"))
            .put("PROJECT_ID", projectId)
            .put("FIRST_DAY_OF_MONTH", logTableFormatter.format(firstDayOfMonth))
            .put("LAST_DAY_OF_MONTH", logTableFormatter.format(lastDayOfMonth))
            .build();
    queriesBuilder.put(getTableName(EPP_METRICS, yearMonth), eppQuery);

    String rdapQuery =
        SqlTemplate.create(getQueryFromFile(RDAP_COUNTS + ".sql"))
            .put("PROJECT_ID", projectId)
            .put("ICANN_REPORTING_DATA_SET", icannReportingDataSet)
            .put("MONTHLY_LOGS_TABLE", getTableName(MONTHLY_LOGS, yearMonth))
            .build();
    queriesBuilder.put(getTableName(RDAP_COUNTS, yearMonth), rdapQuery);

    SqlTemplate aggregateQuery =
        SqlTemplate.create(getQueryFromFile(ACTIVITY_REPORT_AGGREGATION + ".sql"))
            .put("PROJECT_ID", projectId)
            .put(
                "REGISTRAR_OPERATING_STATUS_TABLE",
                getTableName(REGISTRAR_OPERATING_STATUS, yearMonth))
            .put("ICANN_REPORTING_DATA_SET", icannReportingDataSet)
            .put("DNS_COUNTS_TABLE", getTableName(DNS_COUNTS, yearMonth))
            .put("EPP_METRICS_TABLE", getTableName(EPP_METRICS, yearMonth))
            .put("RDAP_COUNTS_TABLE", getTableName(RDAP_COUNTS, yearMonth));

    queriesBuilder.put(
        getTableName(ACTIVITY_REPORT_AGGREGATION, yearMonth), aggregateQuery.build());

    return queriesBuilder.build();
  }

  void prepareForQuery(YearMonth yearMonth) throws InterruptedException {
    dnsCountQueryCoordinator.prepareForQuery(yearMonth);
  }
}
