/*
 * 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.service;

import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;

import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.gravitino.Entity;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.RelationalEntity;
import org.apache.gravitino.SupportsRelationOperations;
import org.apache.gravitino.authorization.AuthorizationUtils;
import org.apache.gravitino.meta.UserEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.po.GroupPO;
import org.apache.gravitino.storage.relational.po.OwnerRelForDeletion;
import org.apache.gravitino.storage.relational.po.OwnerRelPO;
import org.apache.gravitino.storage.relational.po.UserOwnerRelPO;
import org.apache.gravitino.storage.relational.po.UserPO;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.utils.NameIdentifierUtil;

/** This class is an utilization class to retrieve owner relation. */
public class OwnerMetaService {

  private OwnerMetaService() {}

  private static final OwnerMetaService INSTANCE = new OwnerMetaService();

  public static OwnerMetaService getInstance() {
    return INSTANCE;
  }

  @Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME, baseMetricName = "getOwner")
  public Optional<Entity> getOwner(NameIdentifier identifier, Entity.EntityType type) {

    Long entityId = EntityIdService.getEntityId(identifier, type);

    UserPO userPO =
        SessionUtils.getWithoutCommit(
            OwnerMetaMapper.class,
            mapper -> mapper.selectUserOwnerMetaByMetadataObjectIdAndType(entityId, type.name()));

    if (userPO != null) {
      return Optional.of(
          POConverters.fromUserPO(
              userPO,
              Collections.emptyList(),
              AuthorizationUtils.ofUserNamespace(NameIdentifierUtil.getMetalake(identifier))));
    }

    GroupPO groupPO =
        SessionUtils.getWithoutCommit(
            OwnerMetaMapper.class,
            mapper -> mapper.selectGroupOwnerMetaByMetadataObjectIdAndType(entityId, type.name()));

    if (groupPO != null) {
      return Optional.of(
          POConverters.fromGroupPO(
              groupPO,
              Collections.emptyList(),
              AuthorizationUtils.ofGroupNamespace(NameIdentifierUtil.getMetalake(identifier))));
    }

    return Optional.empty();
  }

  @Monitored(
      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
      baseMetricName = "batchGetOwner")
  public List<RelationalEntity<?>> batchGetOwner(
      List<NameIdentifier> identifiers, Entity.EntityType type) {
    if (CollectionUtils.isEmpty(identifiers)) {
      return new ArrayList<>();
    }
    String metalake = NameIdentifierUtil.getMetalake(identifiers.get(0));
    for (NameIdentifier identifier : identifiers) {
      Preconditions.checkArgument(
          Objects.equals(NameIdentifierUtil.getMetalake(identifier), metalake),
          "identifiers should in one metalake");
    }
    List<RelationalEntity<?>> result = new ArrayList<>();
    Map<Long, NameIdentifier> nameIdentifierMap = new HashMap<>();
    List<Long> entityIds =
        identifiers.stream()
            .map(
                identifier -> {
                  long entityId = EntityIdService.getEntityId(identifier, type);
                  nameIdentifierMap.put(entityId, identifier);
                  return entityId;
                })
            .collect(Collectors.toList());

    // Get user owners
    List<UserOwnerRelPO> userPOList =
        SessionUtils.getWithoutCommit(
            OwnerMetaMapper.class,
            mapper ->
                mapper.batchSelectUserOwnerMetaByMetadataObjectIdAndType(entityIds, type.name()));
    if (CollectionUtils.isNotEmpty(userPOList)) {
      userPOList.forEach(
          userPO -> {
            UserEntity userEntity =
                POConverters.fromUserPO(
                    userPO, Collections.emptyList(), AuthorizationUtils.ofUserNamespace(metalake));
            result.add(
                new RelationalEntity<>(
                    SupportsRelationOperations.Type.OWNER_REL,
                    nameIdentifierMap.get(userPO.getMetadataObjectId()),
                    type,
                    userEntity));
          });
    }

    // TODO: Add batch support for group owners when GroupOwnerRelPO and batch method are available
    // For now, we only handle user owners in batch mode

    return result;
  }

  @Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME, baseMetricName = "setOwner")
  public void setOwner(
      NameIdentifier entity,
      Entity.EntityType entityType,
      NameIdentifier owner,
      Entity.EntityType ownerType) {
    long metalakeId =
        MetalakeMetaService.getInstance()
            .getMetalakeIdByName(NameIdentifierUtil.getMetalake(entity));

    Long entityId = EntityIdService.getEntityId(entity, entityType);
    Long ownerId = EntityIdService.getEntityId(owner, ownerType);

    OwnerRelPO ownerRelPO =
        POConverters.initializeOwnerRelPOsWithVersion(
            metalakeId, ownerType.name(), ownerId, entityType.name(), entityId);
    SessionUtils.doMultipleWithCommit(
        () ->
            SessionUtils.doWithoutCommit(
                OwnerMetaMapper.class,
                mapper ->
                    mapper.softDeleteOwnerRelByMetadataObjectIdAndType(
                        entityId,
                        NameIdentifierUtil.toMetadataObject(entity, entityType).type().name())),
        () ->
            SessionUtils.doWithoutCommit(
                OwnerMetaMapper.class, mapper -> mapper.insertOwnerRel(ownerRelPO)));
  }

  @Monitored(
      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
      baseMetricName = "batchSetOwner")
  public void batchSetOwners(
      List<NameIdentifier> ownedObjects,
      Entity.EntityType ownedObjectType,
      NameIdentifier ownerIdent,
      Entity.EntityType ownerType) {
    if (CollectionUtils.isEmpty(ownedObjects)) {
      return;
    }

    String metalake = NameIdentifierUtil.getMetalake(ownedObjects.get(0));
    for (NameIdentifier entity : ownedObjects) {
      Preconditions.checkArgument(
          Objects.equals(NameIdentifierUtil.getMetalake(entity), metalake),
          "All owned objects must be in the same metalake");
    }

    long metalakeId = MetalakeMetaService.getInstance().getMetalakeIdByName(metalake);
    Long ownerId = EntityIdService.getEntityId(ownerIdent, ownerType);

    List<OwnerRelForDeletion> deletions = new ArrayList<>(ownedObjects.size());
    List<OwnerRelPO> ownerRelPOs = new ArrayList<>(ownedObjects.size());
    for (NameIdentifier entity : ownedObjects) {
      Long entityId = EntityIdService.getEntityId(entity, ownedObjectType);
      deletions.add(
          new OwnerRelForDeletion(
              entityId,
              NameIdentifierUtil.toMetadataObject(entity, ownedObjectType).type().name()));
      ownerRelPOs.add(
          POConverters.initializeOwnerRelPOsWithVersion(
              metalakeId, ownerType.name(), ownerId, ownedObjectType.name(), entityId));
    }

    SessionUtils.doMultipleWithCommit(
        () ->
            SessionUtils.doWithoutCommit(
                OwnerMetaMapper.class,
                mapper -> mapper.batchSoftDeleteOwnerRelByMetadataObjects(deletions)),
        () ->
            SessionUtils.doWithoutCommit(
                OwnerMetaMapper.class, mapper -> mapper.batchInsertOwnerRels(ownerRelPOs)));
  }
}
