/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.gravitino.iceberg.service.cleanup.mapper;

import com.google.common.collect.ImmutableMap;
import java.util.Map;
import org.apache.gravitino.iceberg.service.cleanup.mapper.provider.base.IcebergCleanupJobBaseSQLProvider;
import org.apache.gravitino.iceberg.service.cleanup.po.IcebergCleanupJobPO;
import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;
import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
import org.apache.ibatis.annotations.Param;

/**
 * Supplies the SQL for {@link IcebergCleanupJobMapper}, dispatching by the entity store's
 * configured JDBC backend. The statements are written with portable, parameterized SQL (the row id
 * and all timestamps are generated by the application, not the database), so the {@link
 * IcebergCleanupJobBaseSQLProvider} serves MySQL, H2, and PostgreSQL alike. A backend that ever
 * needs a divergent statement can be registered here by mapping its {@link JDBCBackendType} to an
 * {@link IcebergCleanupJobBaseSQLProvider} subclass that overrides only the affected methods.
 */
public class IcebergCleanupJobSQLProviderFactory {

  private static final IcebergCleanupJobBaseSQLProvider BASE_PROVIDER =
      new IcebergCleanupJobBaseSQLProvider();

  private static final Map<JDBCBackendType, IcebergCleanupJobBaseSQLProvider> PROVIDERS =
      ImmutableMap.of(
          JDBCBackendType.MYSQL, BASE_PROVIDER,
          JDBCBackendType.H2, BASE_PROVIDER,
          JDBCBackendType.POSTGRESQL, BASE_PROVIDER);

  private static IcebergCleanupJobBaseSQLProvider getProvider() {
    String databaseId =
        SqlSessionFactoryHelper.getInstance()
            .getSqlSessionFactory()
            .getConfiguration()
            .getDatabaseId();
    return PROVIDERS.get(JDBCBackendType.fromString(databaseId));
  }

  public static String insertCleanupJob(@Param("po") IcebergCleanupJobPO po) {
    return getProvider().insertCleanupJob(po);
  }

  public static String selectCandidateJobs(
      @Param("heartbeatExpiry") long heartbeatExpiry, @Param("window") int window) {
    return getProvider().selectCandidateJobs(heartbeatExpiry, window);
  }

  public static String markRunning(
      @Param("id") long id,
      @Param("now") long now,
      @Param("heartbeatExpiry") long heartbeatExpiry) {
    return getProvider().markRunning(id, now, heartbeatExpiry);
  }

  public static String markFinished(
      @Param("id") long id,
      @Param("state") String state,
      @Param("reason") String reason,
      @Param("now") long now,
      @Param("heartbeat") long heartbeat) {
    return getProvider().markFinished(id, state, reason, now, heartbeat);
  }

  public static String recordFailure(
      @Param("id") long id,
      @Param("reason") String reason,
      @Param("maxAttempts") int maxAttempts,
      @Param("now") long now,
      @Param("heartbeat") long heartbeat) {
    return getProvider().recordFailure(id, reason, maxAttempts, now, heartbeat);
  }

  public static String heartbeat(
      @Param("id") long id, @Param("lastHeartbeat") long lastHeartbeat, @Param("now") long now) {
    return getProvider().heartbeat(id, lastHeartbeat, now);
  }

  public static String selectUnfinishedJobId(
      @Param("catalogId") long catalogId,
      @Param("namespace") String namespace,
      @Param("table") String table) {
    return getProvider().selectUnfinishedJobId(catalogId, namespace, table);
  }

  public static String deleteFinishedJobsByLegacyTimeline(
      @Param("legacyTimeline") long legacyTimeline) {
    return getProvider().deleteFinishedJobsByLegacyTimeline(legacyTimeline);
  }

  public static String selectState(@Param("id") long id) {
    return getProvider().selectState(id);
  }
}
