/*
 * 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.storage.relational.mapper.provider.base;

import static org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper.TABLE_NAME;

import java.util.List;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
import org.apache.gravitino.storage.relational.po.SchemaPO;
import org.apache.ibatis.annotations.Param;

public class SchemaMetaBaseSQLProvider {
  public String listSchemaPOsByCatalogId(@Param("catalogId") Long catalogId) {
    return "SELECT schema_id as schemaId, schema_name as schemaName,"
        + " metalake_id as metalakeId, catalog_id as catalogId,"
        + " schema_comment as schemaComment, properties, audit_info as auditInfo,"
        + " current_version as currentVersion, last_version as lastVersion,"
        + " deleted_at as deletedAt"
        + " FROM "
        + TABLE_NAME
        + " WHERE catalog_id = #{catalogId} AND deleted_at = 0";
  }

  public String listSchemaPOsByFullQualifiedName(
      @Param("metalakeName") String metalakeName, @Param("catalogName") String catalogName) {
    return """
        SELECT
            mm.metalake_id as metalakeId,
            cm.catalog_id as catalogId,
            sm.schema_id as schemaId,
            sm.schema_name as schemaName,
            sm.schema_comment as schemaComment,
            sm.properties as properties,
            sm.audit_info as auditInfo,
            sm.current_version as currentVersion,
            sm.last_version as lastVersion,
            sm.deleted_at as deletedAt
        FROM
            %s mm
        INNER JOIN
            %s cm ON mm.metalake_id = cm.metalake_id
            AND cm.catalog_name = #{catalogName}
            AND cm.deleted_at = 0
        LEFT JOIN
            %s sm ON cm.catalog_id = sm.catalog_id
            AND sm.deleted_at = 0
        WHERE
            mm.metalake_name = #{metalakeName}
            AND mm.deleted_at = 0;
            """
        .formatted(MetalakeMetaMapper.TABLE_NAME, CatalogMetaMapper.TABLE_NAME, TABLE_NAME);
  }

  public String listSchemaPOsBySchemaIds(@Param("schemaIds") List<Long> schemaIds) {
    return "<script>"
        + "SELECT schema_id as schemaId, schema_name as schemaName,"
        + " metalake_id as metalakeId, catalog_id as catalogId,"
        + " schema_comment as schemaComment, properties, audit_info as auditInfo,"
        + " current_version as currentVersion, last_version as lastVersion,"
        + " deleted_at as deletedAt"
        + " FROM "
        + TABLE_NAME
        + " WHERE schema_id IN ("
        + "<foreach collection='schemaIds' item='schemaId' separator=','>"
        + "#{schemaId}"
        + "</foreach>"
        + ")"
        + " AND deleted_at = 0"
        + "</script>";
  }

  public String listSchemaPOsByCatalogIdAndNamePrefix(
      @Param("catalogId") Long catalogId,
      @Param("schemaName") String schemaName,
      @Param("descendantPrefix") String descendantPrefix) {
    return "SELECT schema_id as schemaId, schema_name as schemaName,"
        + " metalake_id as metalakeId, catalog_id as catalogId,"
        + " schema_comment as schemaComment, properties, audit_info as auditInfo,"
        + " current_version as currentVersion, last_version as lastVersion,"
        + " deleted_at as deletedAt"
        + " FROM "
        + TABLE_NAME
        + " WHERE catalog_id = #{catalogId}"
        // The descendantPrefix has its LIKE metacharacters escaped with '!' by the caller
        // (SchemaPOStorageOps#escapeLikeMetacharacters), so '!' is declared as the ESCAPE
        // character to keep the prefix match literal across MySQL, H2, and PostgreSQL.
        + " AND (schema_name = #{schemaName}"
        + " OR schema_name LIKE CONCAT(#{descendantPrefix}, '%') ESCAPE '!')"
        + " AND deleted_at = 0";
  }

  public String selectSchemaIdByCatalogIdAndName(
      @Param("catalogId") Long catalogId, @Param("schemaName") String name) {
    return "SELECT schema_id as schemaId FROM "
        + TABLE_NAME
        + " WHERE catalog_id = #{catalogId} AND schema_name = #{schemaName}"
        + " AND deleted_at = 0";
  }

  public String selectSchemaMetaByCatalogIdAndName(
      @Param("catalogId") Long catalogId, @Param("schemaName") String name) {
    return "SELECT schema_id as schemaId, schema_name as schemaName,"
        + " metalake_id as metalakeId, catalog_id as catalogId,"
        + " schema_comment as schemaComment, properties, audit_info as auditInfo,"
        + " current_version as currentVersion, last_version as lastVersion,"
        + " deleted_at as deletedAt"
        + " FROM "
        + TABLE_NAME
        + " WHERE catalog_id = #{catalogId} AND schema_name = #{schemaName} AND deleted_at = 0";
  }

  public String selectSchemaByFullQualifiedName(
      @Param("metalakeName") String metalakeName,
      @Param("catalogName") String catalogName,
      @Param("schemaName") String schemaName) {
    return """
        SELECT
            mm.metalake_id as metalakeId,
            cm.catalog_id as catalogId,
            sm.schema_id as schemaId,
            sm.schema_name as schemaName,
            sm.schema_comment as schemaComment,
            sm.properties as properties,
            sm.audit_info as auditInfo,
            sm.current_version as currentVersion,
            sm.last_version as lastVersion,
            sm.deleted_at as deletedAt
        FROM
            %s mm
        INNER JOIN
            %s cm ON mm.metalake_id = cm.metalake_id
            AND cm.catalog_name = #{catalogName}
            AND cm.deleted_at = 0
        LEFT JOIN
            %s sm ON cm.catalog_id = sm.catalog_id
            AND sm.schema_name = #{schemaName}
            AND sm.deleted_at = 0
        WHERE
            mm.metalake_name = #{metalakeName}
            AND mm.deleted_at = 0;
            """
        .formatted(MetalakeMetaMapper.TABLE_NAME, CatalogMetaMapper.TABLE_NAME, TABLE_NAME);
  }

  public String selectSchemaMetaById(@Param("schemaId") Long schemaId) {
    return "SELECT schema_id as schemaId, schema_name as schemaName,"
        + " metalake_id as metalakeId, catalog_id as catalogId,"
        + " schema_comment as schemaComment, properties, audit_info as auditInfo,"
        + " current_version as currentVersion, last_version as lastVersion,"
        + " deleted_at as deletedAt"
        + " FROM "
        + TABLE_NAME
        + " WHERE schema_id = #{schemaId} AND deleted_at = 0";
  }

  public String insertSchemaMeta(@Param("schemaMeta") SchemaPO schemaPO) {
    return "INSERT INTO "
        + TABLE_NAME
        + " (schema_id, schema_name, metalake_id,"
        + " catalog_id, schema_comment, properties, audit_info,"
        + " current_version, last_version, deleted_at)"
        + " VALUES ("
        + " #{schemaMeta.schemaId},"
        + " #{schemaMeta.schemaName},"
        + " #{schemaMeta.metalakeId},"
        + " #{schemaMeta.catalogId},"
        + " #{schemaMeta.schemaComment},"
        + " #{schemaMeta.properties},"
        + " #{schemaMeta.auditInfo},"
        + " #{schemaMeta.currentVersion},"
        + " #{schemaMeta.lastVersion},"
        + " #{schemaMeta.deletedAt}"
        + " )";
  }

  public String insertSchemaMetaOnDuplicateKeyUpdate(@Param("schemaMeta") SchemaPO schemaPO) {
    return "INSERT INTO "
        + TABLE_NAME
        + " (schema_id, schema_name, metalake_id,"
        + " catalog_id, schema_comment, properties, audit_info,"
        + " current_version, last_version, deleted_at)"
        + " VALUES ("
        + " #{schemaMeta.schemaId},"
        + " #{schemaMeta.schemaName},"
        + " #{schemaMeta.metalakeId},"
        + " #{schemaMeta.catalogId},"
        + " #{schemaMeta.schemaComment},"
        + " #{schemaMeta.properties},"
        + " #{schemaMeta.auditInfo},"
        + " #{schemaMeta.currentVersion},"
        + " #{schemaMeta.lastVersion},"
        + " #{schemaMeta.deletedAt}"
        + " )"
        + " ON DUPLICATE KEY UPDATE"
        + " schema_name = #{schemaMeta.schemaName},"
        + " metalake_id = #{schemaMeta.metalakeId},"
        + " catalog_id = #{schemaMeta.catalogId},"
        + " schema_comment = #{schemaMeta.schemaComment},"
        + " properties = #{schemaMeta.properties},"
        + " audit_info = #{schemaMeta.auditInfo},"
        + " current_version = #{schemaMeta.currentVersion},"
        + " last_version = #{schemaMeta.lastVersion},"
        + " deleted_at = #{schemaMeta.deletedAt}";
  }

  public String batchInsertSchemaMeta(@Param("schemaMetas") List<SchemaPO> schemaMetas) {
    return "<script>"
        + "INSERT INTO "
        + TABLE_NAME
        + " (schema_id, schema_name, metalake_id, catalog_id, schema_comment,"
        + " properties, audit_info, current_version, last_version, deleted_at) VALUES "
        + "<foreach collection='schemaMetas' item='po' separator=','>"
        + "(#{po.schemaId}, #{po.schemaName}, #{po.metalakeId}, #{po.catalogId},"
        + " #{po.schemaComment}, #{po.properties}, #{po.auditInfo},"
        + " #{po.currentVersion}, #{po.lastVersion}, #{po.deletedAt})"
        + "</foreach>"
        + "</script>";
  }

  public String batchInsertSchemaMetaOnDuplicateKeyUpdate(
      @Param("schemaMetas") List<SchemaPO> schemaMetas) {
    return "<script>"
        + "INSERT INTO "
        + TABLE_NAME
        + " (schema_id, schema_name, metalake_id, catalog_id, schema_comment,"
        + " properties, audit_info, current_version, last_version, deleted_at) VALUES "
        + "<foreach collection='schemaMetas' item='po' separator=','>"
        + "(#{po.schemaId}, #{po.schemaName}, #{po.metalakeId}, #{po.catalogId},"
        + " #{po.schemaComment}, #{po.properties}, #{po.auditInfo},"
        + " #{po.currentVersion}, #{po.lastVersion}, #{po.deletedAt})"
        + "</foreach>"
        + " ON DUPLICATE KEY UPDATE"
        + " schema_name = VALUES(schema_name),"
        + " metalake_id = VALUES(metalake_id),"
        + " catalog_id = VALUES(catalog_id),"
        + " schema_comment = VALUES(schema_comment),"
        + " properties = VALUES(properties),"
        + " audit_info = VALUES(audit_info),"
        + " current_version = VALUES(current_version),"
        + " last_version = VALUES(last_version),"
        + " deleted_at = VALUES(deleted_at)"
        + "</script>";
  }

  public String updateSchemaMeta(
      @Param("newSchemaMeta") SchemaPO newSchemaPO, @Param("oldSchemaMeta") SchemaPO oldSchemaPO) {
    return "UPDATE "
        + TABLE_NAME
        + " SET schema_name = #{newSchemaMeta.schemaName},"
        + " metalake_id = #{newSchemaMeta.metalakeId},"
        + " catalog_id = #{newSchemaMeta.catalogId},"
        + " schema_comment = #{newSchemaMeta.schemaComment},"
        + " properties = #{newSchemaMeta.properties},"
        + " audit_info = #{newSchemaMeta.auditInfo},"
        + " current_version = #{newSchemaMeta.currentVersion},"
        + " last_version = #{newSchemaMeta.lastVersion},"
        + " deleted_at = #{newSchemaMeta.deletedAt}"
        + " WHERE schema_id = #{oldSchemaMeta.schemaId}"
        + " AND schema_name = #{oldSchemaMeta.schemaName}"
        + " AND metalake_id = #{oldSchemaMeta.metalakeId}"
        + " AND catalog_id = #{oldSchemaMeta.catalogId}"
        + " AND (schema_comment = #{oldSchemaMeta.schemaComment}"
        + "   OR (schema_comment IS NULL and #{oldSchemaMeta.schemaComment} IS NULL))"
        + " AND properties = #{oldSchemaMeta.properties}"
        + " AND audit_info = #{oldSchemaMeta.auditInfo}"
        + " AND current_version = #{oldSchemaMeta.currentVersion}"
        + " AND last_version = #{oldSchemaMeta.lastVersion}"
        + " AND deleted_at = 0";
  }

  public String softDeleteSchemaMetasBySchemaIds(@Param("schemaIds") List<Long> schemaIds) {
    return "<script>"
        + "UPDATE "
        + TABLE_NAME
        + " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
        + " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"
        + " WHERE schema_id IN ("
        + "<foreach collection='schemaIds' item='schemaId' separator=','>"
        + "#{schemaId}"
        + "</foreach>"
        + ") AND deleted_at = 0"
        + "</script>";
  }

  public String softDeleteSchemaMetasByMetalakeId(@Param("metalakeId") Long metalakeId) {
    return "UPDATE "
        + TABLE_NAME
        + " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
        + " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"
        + " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";
  }

  public String softDeleteSchemaMetasByCatalogId(@Param("catalogId") Long catalogId) {
    return "UPDATE "
        + TABLE_NAME
        + " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
        + " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"
        + " WHERE catalog_id = #{catalogId} AND deleted_at = 0";
  }

  public String deleteSchemaMetasByLegacyTimeline(
      @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {
    return "DELETE FROM "
        + TABLE_NAME
        + " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit}";
  }

  public String selectSchemaIdByMetalakeNameAndCatalogNameAndSchemaName(
      @Param("metalakeName") String metalakeName,
      @Param("catalogName") String catalogName,
      @Param("schemaName") String schemaName) {
    return "SELECT metalake_meta.metalake_id as metalakeId, catalog_meta.catalog_id as catalogId,"
        + " schema_id as schemaId"
        + " FROM metalake_meta"
        + " JOIN catalog_meta ON metalake_meta.metalake_id = catalog_meta.metalake_id"
        + " JOIN schema_meta ON catalog_meta.catalog_id = schema_meta.catalog_id"
        + " WHERE metalake_name = #{metalakeName}"
        + " AND catalog_name = #{catalogName}"
        + " AND schema_name = #{schemaName}"
        + " AND schema_meta.deleted_at = 0"
        + " AND catalog_meta.deleted_at = 0"
        + " AND metalake_meta.deleted_at = 0";
  }

  public String batchSelectSchemaByIdentifier(
      @Param("metalakeName") String metalakeName,
      @Param("catalogName") String catalogName,
      @Param("schemaNames") List<String> schemaNames) {
    return "<script>"
        + "SELECT sm.schema_id as schemaId, sm.schema_name as schemaName,"
        + " sm.metalake_id as metalakeId, sm.catalog_id as catalogId,"
        + " sm.schema_comment as schemaComment, sm.properties, sm.audit_info as auditInfo,"
        + " sm.current_version as currentVersion, sm.last_version as lastVersion,"
        + " sm.deleted_at as deletedAt"
        + " FROM "
        + TABLE_NAME
        + " sm"
        + " JOIN "
        + CatalogMetaMapper.TABLE_NAME
        + " cm ON sm.catalog_id = cm.catalog_id"
        + " JOIN "
        + MetalakeMetaMapper.TABLE_NAME
        + " mm ON cm.metalake_id = mm.metalake_id"
        + " WHERE mm.metalake_name = #{metalakeName}"
        + " AND cm.catalog_name = #{catalogName}"
        + " AND sm.schema_name IN ("
        + "<foreach collection='schemaNames' item='schemaName' separator=','>"
        + "#{schemaName}"
        + "</foreach>"
        + " )"
        + " AND sm.deleted_at = 0 AND cm.deleted_at = 0 AND mm.deleted_at = 0"
        + "</script>";
  }
}
