/*
 * 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.ViewMetaMapper.TABLE_NAME;
import static org.apache.gravitino.storage.relational.mapper.ViewMetaMapper.VERSION_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.mapper.SchemaMetaMapper;
import org.apache.gravitino.storage.relational.po.ViewPO;
import org.apache.ibatis.annotations.Param;

public class ViewMetaBaseSQLProvider {

  public String listViewPOsBySchemaId(@Param("schemaId") Long schemaId) {
    return "SELECT vm.view_id, vm.view_name, vm.metalake_id, vm.catalog_id, vm.schema_id,"
        + " vm.current_version, vm.last_version, vm.audit_info, vm.deleted_at,"
        + " vi.id, vi.metalake_id as version_metalake_id, vi.catalog_id as version_catalog_id,"
        + " vi.schema_id as version_schema_id, vi.view_id as version_view_id,"
        + " vi.version, vi.view_comment, vi.columns, vi.properties,"
        + " vi.default_catalog, vi.default_schema, vi.representations,"
        + " vi.audit_info as version_audit_info, vi.deleted_at as version_deleted_at"
        + " FROM "
        + TABLE_NAME
        + " vm INNER JOIN "
        + VERSION_TABLE_NAME
        + " vi ON vm.view_id = vi.view_id AND vm.current_version = vi.version"
        + " WHERE vm.schema_id = #{schemaId} AND vm.deleted_at = 0 AND vi.deleted_at = 0";
  }

  public String listViewPOsByFullQualifiedName(
      @Param("metalakeName") String metalakeName,
      @Param("catalogName") String catalogName,
      @Param("schemaName") String schemaName) {
    return """
        SELECT
            mm.metalake_id,
            cm.catalog_id,
            sm.schema_id,
            vm.view_id,
            vm.view_name,
            vm.current_version,
            vm.last_version,
            vm.audit_info,
            vm.deleted_at,
            vi.id,
            vi.metalake_id as version_metalake_id,
            vi.catalog_id as version_catalog_id,
            vi.schema_id as version_schema_id,
            vi.view_id as version_view_id,
            vi.version,
            vi.view_comment,
            vi.columns,
            vi.properties,
            vi.default_catalog,
            vi.default_schema,
            vi.representations,
            vi.audit_info as version_audit_info,
            vi.deleted_at as version_deleted_at
        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
        LEFT JOIN
            %s vm ON sm.schema_id = vm.schema_id
            AND vm.deleted_at = 0
        LEFT JOIN
            %s vi ON vm.view_id = vi.view_id
            AND vm.current_version = vi.version
            AND vi.deleted_at = 0
        WHERE
            mm.metalake_name = #{metalakeName}
            AND mm.deleted_at = 0
        """
        .formatted(
            MetalakeMetaMapper.TABLE_NAME,
            CatalogMetaMapper.TABLE_NAME,
            SchemaMetaMapper.TABLE_NAME,
            TABLE_NAME,
            VERSION_TABLE_NAME);
  }

  public String selectViewIdBySchemaIdAndName(
      @Param("schemaId") Long schemaId, @Param("viewName") String name) {
    return "SELECT view_id as viewId FROM "
        + TABLE_NAME
        + " WHERE schema_id = #{schemaId} AND view_name = #{viewName}"
        + " AND deleted_at = 0";
  }

  public String selectViewMetaBySchemaIdAndName(
      @Param("schemaId") Long schemaId, @Param("viewName") String name) {
    return "SELECT vm.view_id, vm.view_name, vm.metalake_id, vm.catalog_id, vm.schema_id,"
        + " vm.current_version, vm.last_version, vm.audit_info, vm.deleted_at,"
        + " vi.id, vi.metalake_id as version_metalake_id, vi.catalog_id as version_catalog_id,"
        + " vi.schema_id as version_schema_id, vi.view_id as version_view_id,"
        + " vi.version, vi.view_comment, vi.columns, vi.properties,"
        + " vi.default_catalog, vi.default_schema, vi.representations,"
        + " vi.audit_info as version_audit_info, vi.deleted_at as version_deleted_at"
        + " FROM "
        + TABLE_NAME
        + " vm INNER JOIN "
        + VERSION_TABLE_NAME
        + " vi ON vm.view_id = vi.view_id AND vm.current_version = vi.version"
        + " WHERE vm.schema_id = #{schemaId} AND vm.view_name = #{viewName}"
        + " AND vm.deleted_at = 0 AND vi.deleted_at = 0";
  }

  public String insertViewMeta(@Param("viewMeta") ViewPO viewPO) {
    return "INSERT INTO "
        + TABLE_NAME
        + " (view_id, view_name, metalake_id,"
        + " catalog_id, schema_id,"
        + " current_version, last_version, audit_info, deleted_at)"
        + " VALUES ("
        + " #{viewMeta.viewId},"
        + " #{viewMeta.viewName},"
        + " #{viewMeta.metalakeId},"
        + " #{viewMeta.catalogId},"
        + " #{viewMeta.schemaId},"
        + " #{viewMeta.currentVersion},"
        + " #{viewMeta.lastVersion},"
        + " #{viewMeta.auditInfo},"
        + " #{viewMeta.deletedAt}"
        + " )";
  }

  public String insertViewMetaOnDuplicateKeyUpdate(@Param("viewMeta") ViewPO viewPO) {
    return "INSERT INTO "
        + TABLE_NAME
        + " (view_id, view_name, metalake_id,"
        + " catalog_id, schema_id,"
        + " current_version, last_version, audit_info, deleted_at)"
        + " VALUES ("
        + " #{viewMeta.viewId},"
        + " #{viewMeta.viewName},"
        + " #{viewMeta.metalakeId},"
        + " #{viewMeta.catalogId},"
        + " #{viewMeta.schemaId},"
        + " #{viewMeta.currentVersion},"
        + " #{viewMeta.lastVersion},"
        + " #{viewMeta.auditInfo},"
        + " #{viewMeta.deletedAt}"
        + " )"
        + " ON DUPLICATE KEY UPDATE"
        + " view_name = #{viewMeta.viewName},"
        + " metalake_id = #{viewMeta.metalakeId},"
        + " catalog_id = #{viewMeta.catalogId},"
        + " schema_id = #{viewMeta.schemaId},"
        + " current_version = #{viewMeta.currentVersion},"
        + " last_version = #{viewMeta.lastVersion},"
        + " audit_info = #{viewMeta.auditInfo},"
        + " deleted_at = #{viewMeta.deletedAt}";
  }

  public String updateViewMeta(
      @Param("newViewMeta") ViewPO newViewPO, @Param("oldViewMeta") ViewPO oldViewPO) {
    return "UPDATE "
        + TABLE_NAME
        + " SET view_name = #{newViewMeta.viewName}, "
        + " schema_id = #{newViewMeta.schemaId}, "
        + " current_version = #{newViewMeta.currentVersion}, "
        + " last_version = #{newViewMeta.lastVersion}, "
        + " audit_info = #{newViewMeta.auditInfo}, "
        + " deleted_at = #{newViewMeta.deletedAt} "
        + " WHERE view_id = #{oldViewMeta.viewId} "
        + " AND current_version = #{oldViewMeta.currentVersion} "
        + " AND deleted_at = 0";
  }

  public String listViewPOsByViewIds(@Param("viewIds") List<Long> viewIds) {
    return "<script>"
        + "SELECT vm.view_id, vm.view_name, vm.metalake_id, vm.catalog_id, vm.schema_id,"
        + " vm.current_version, vm.last_version, vm.audit_info, vm.deleted_at,"
        + " vi.id, vi.metalake_id as version_metalake_id, vi.catalog_id as version_catalog_id,"
        + " vi.schema_id as version_schema_id, vi.view_id as version_view_id,"
        + " vi.version, vi.view_comment, vi.columns, vi.properties,"
        + " vi.default_catalog, vi.default_schema, vi.representations,"
        + " vi.audit_info as version_audit_info, vi.deleted_at as version_deleted_at"
        + " FROM "
        + TABLE_NAME
        + " vm INNER JOIN "
        + VERSION_TABLE_NAME
        + " vi ON vm.view_id = vi.view_id AND vm.current_version = vi.version"
        + " WHERE vm.view_id IN "
        + "<foreach item='viewId' index='index' collection='viewIds' open='(' separator=',' close=')'>"
        + "#{viewId}"
        + "</foreach>"
        + " AND vm.deleted_at = 0 AND vi.deleted_at = 0"
        + "</script>";
  }

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

  public String softDeleteViewMetasByMetalakeId(@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 softDeleteViewMetasByCatalogId(@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 softDeleteViewMetasBySchemaIds(@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 deleteViewMetasByLegacyTimeline(
      @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 selectViewByFullQualifiedName(
      @Param("metalakeName") String metalakeName,
      @Param("catalogName") String catalogName,
      @Param("schemaName") String schemaName,
      @Param("viewName") String viewName) {
    return """
        SELECT
            mm.metalake_id,
            cm.catalog_id,
            sm.schema_id,
            vm.view_id,
            vm.view_name,
            vm.current_version,
            vm.last_version,
            vm.audit_info,
            vm.deleted_at,
            vi.id,
            vi.metalake_id as version_metalake_id,
            vi.catalog_id as version_catalog_id,
            vi.schema_id as version_schema_id,
            vi.view_id as version_view_id,
            vi.version,
            vi.view_comment,
            vi.columns,
            vi.properties,
            vi.default_catalog,
            vi.default_schema,
            vi.representations,
            vi.audit_info as version_audit_info,
            vi.deleted_at as version_deleted_at
        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
        LEFT JOIN
            %s vm ON sm.schema_id = vm.schema_id
            AND vm.view_name = #{viewName}
            AND vm.deleted_at = 0
        LEFT JOIN
            %s vi ON vm.view_id = vi.view_id
            AND vm.current_version = vi.version
            AND vi.deleted_at = 0
        WHERE
            mm.metalake_name = #{metalakeName}
            AND mm.deleted_at = 0
        """
        .formatted(
            MetalakeMetaMapper.TABLE_NAME,
            CatalogMetaMapper.TABLE_NAME,
            SchemaMetaMapper.TABLE_NAME,
            TABLE_NAME,
            VERSION_TABLE_NAME);
  }
}
