/*
 * Copyright 2022 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * 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 org.keycloak.models.map.storage.jpa.authorization.policy.entity;

import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import jakarta.persistence.Basic;
import jakarta.persistence.CascadeType;
import jakarta.persistence.CollectionTable;
import jakarta.persistence.Column;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
import jakarta.persistence.Version;
import org.hibernate.annotations.Type;
import org.keycloak.models.map.authorization.entity.MapPolicyEntity.AbstractMapPolicyEntity;
import org.keycloak.models.map.common.DeepCloner;
import org.keycloak.models.map.common.StringKeyConverter;
import org.keycloak.models.map.common.UuidValidator;
import org.keycloak.models.map.storage.jpa.Constants;
import org.keycloak.models.map.storage.jpa.JpaRootVersionedEntity;
import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;
import org.keycloak.representations.idm.authorization.DecisionStrategy;
import org.keycloak.representations.idm.authorization.Logic;

/**
 * There are some fields marked by {@code @Column(insertable = false, updatable = false)}.
 * Those fields are automatically generated by database from json field,
 * therefore marked as non-insertable and non-updatable to instruct hibernate.
 */
@Entity
@Table(name = "kc_authz_policy", uniqueConstraints = {@UniqueConstraint(columnNames = {"realmId", "resourceServerId", "name"})})
public class JpaPolicyEntity extends AbstractMapPolicyEntity implements JpaRootVersionedEntity {

    @Id
    @Column
    private UUID id;

    //used for implicit optimistic locking
    @Version
    @Column
    private int version;

    @Type(JsonbType.class)
    @Column(columnDefinition = "jsonb")
    private final JpaPolicyMetadata metadata;

    @Column(insertable = false, updatable = false)
    @Basic(fetch = FetchType.LAZY)
    private Integer entityVersion;

    @Column(insertable = false, updatable = false)
    @Basic(fetch = FetchType.LAZY)
    private String realmId;

    @Column(insertable = false, updatable = false)
    @Basic(fetch = FetchType.LAZY)
    private UUID resourceServerId;

    @Column(insertable = false, updatable = false)
    @Basic(fetch = FetchType.LAZY)
    private String name;

    @Column(insertable = false, updatable = false)
    @Basic(fetch = FetchType.LAZY)
    private String owner;

    @Column(insertable = false, updatable = false)
    @Basic(fetch = FetchType.LAZY)
    private String type;

    //TODO starts here
    //possible future optimization: use @OneToMany to avoid reinserting entries after every change, see: https://thorben-janssen.com/hibernate-tips-elementcollection/
    @Column(name = "scope_id")
    @ElementCollection
    @CollectionTable(name = "kc_authz_policy_scope", joinColumns = @JoinColumn(name = "policy_id", nullable = false))
    private final Set<UUID> scopeIds = new HashSet<>();

    @Column(name = "resource_id")
    @ElementCollection
    @CollectionTable(name = "kc_authz_policy_resource", joinColumns = @JoinColumn(name = "policy_id", nullable = false))
    private final Set<UUID> resourceIds = new HashSet<>();

    @Column(name = "associated_policy_id")
    @ElementCollection
    @CollectionTable(name = "kc_authz_policy_associated_policy", joinColumns = @JoinColumn(name = "policy_id", nullable = false))
    private final Set<UUID> policyIds = new HashSet<>();
    //TODO ends here

    @OneToMany(mappedBy = "root", cascade = CascadeType.PERSIST, orphanRemoval = true)
    private final Set<JpaPolicyConfigEntity> config = new HashSet<>();

    /**
     * No-argument constructor, used by hibernate to instantiate entities.
     */
    public JpaPolicyEntity() {
        this.metadata = new JpaPolicyMetadata();
    }

    public JpaPolicyEntity(DeepCloner cloner) {
        this.metadata = new JpaPolicyMetadata(cloner);
    }

    /**
     * Used by hibernate when calling cb.construct from read(QueryParameters) method.
     * It is used to select object without metadata(json) field.
     */
    public JpaPolicyEntity(UUID id, int version, Integer entityVersion, String realmId, 
            UUID resourceServerId, String name, String owner, String type) {
        this.id = id;
        this.version = version;
        this.entityVersion = entityVersion;
        this.realmId = realmId;
        this.resourceServerId = resourceServerId;
        this.name = name;
        this.owner = owner;
        this.type = type;
        this.metadata = null;
    }

    public boolean isMetadataInitialized() {
        return metadata != null;
    }

    @Override
    public Integer getEntityVersion() {
        if (isMetadataInitialized()) return metadata.getEntityVersion();
        return entityVersion;
    }

    @Override
    public void setEntityVersion(Integer entityVersion) {
        metadata.setEntityVersion(entityVersion);
    }

    @Override
    public Integer getCurrentSchemaVersion() {
        return Constants.CURRENT_SCHEMA_VERSION_AUTHZ_POLICY;
    }

    @Override
    public int getVersion() {
        return version;
    }

    @Override
    public String getId() {
        return id == null ? null : id.toString();
    }

    @Override
    public void setId(String id) {
        String validatedId = UuidValidator.validateAndConvert(id);
        this.id = UUID.fromString(validatedId);
    }

    @Override
    public String getRealmId() {
        if (isMetadataInitialized()) return metadata.getRealmId();
        return realmId;
    }

    @Override
    public void setRealmId(String realmId) {
        metadata.setRealmId(realmId);
    }

    @Override
    public String getResourceServerId() {
        if (isMetadataInitialized()) return metadata.getResourceServerId();
        return resourceServerId == null ? null : resourceServerId.toString();
    }

    @Override
    public void setResourceServerId(String resourceServerId) {
        metadata.setResourceServerId(resourceServerId);
    }

    @Override
    public String getName() {
        if (isMetadataInitialized()) return metadata.getName();
        return name;
    }

    @Override
    public void setName(String name) {
        metadata.setName(name);
    }

    @Override
    public String getType() {
        if (isMetadataInitialized()) return metadata.getType();
        return type;
    }

    @Override
    public void setType(String type) {
        metadata.setType(type);
    }

    @Override
    public String getDescription() {
        return metadata.getDescription();
    }

    @Override
    public void setDescription(String description) {
        metadata.setDescription(description);
    }

    @Override
    public DecisionStrategy getDecisionStrategy() {
        return metadata.getDecisionStrategy();
    }

    @Override
    public void setDecisionStrategy(DecisionStrategy decisionStrategy) {
        metadata.setDecisionStrategy(decisionStrategy);
    }

    @Override
    public Logic getLogic() {
        return metadata.getLogic();
    }

    @Override
    public void setLogic(Logic logic) {
        metadata.setLogic(logic);
    }

    @Override
    public Map<String, String> getConfigs() {
        return Collections.unmodifiableMap(config.stream().collect(Collectors.toMap(JpaPolicyConfigEntity::getName, JpaPolicyConfigEntity::getValue)));
    }

    @Override
    public void setConfigs(Map<String, String> config) {
        this.config.clear();
        if (config == null) return;
        for (Map.Entry<String, String> entry : config.entrySet()) {
            setConfig(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public String getConfig(String name) {
        return config.stream()
                .filter(obj -> Objects.equals(obj.getName(), name))
                .findFirst()
                .map(JpaPolicyConfigEntity::getValue)
                .orElse(null);
    }

    @Override
    public void setConfig(String name, String value) {
        if (name == null || value == null || value.trim().isEmpty()) return;
        JpaPolicyConfigEntity configEntity = new JpaPolicyConfigEntity(this, name, value);
        if (config.contains(configEntity)) config.remove(configEntity);
        config.add(configEntity);
    }

    @Override
    public void removeConfig(String name) {
        config.removeIf(obj -> Objects.equals(obj.getName(), name));
    }

    @Override
    public Set<String> getAssociatedPolicyIds() {
        return policyIds.stream().map(UUID::toString).collect(Collectors.toSet());
    }

    @Override
    public void addAssociatedPolicyId(String policyId) {
        policyIds.add(StringKeyConverter.UUIDKey.INSTANCE.fromString(policyId));
    }

    @Override
    public void removeAssociatedPolicyId(String policyId) {
        policyIds.remove(StringKeyConverter.UUIDKey.INSTANCE.fromString(policyId));
    }

    @Override
    public Set<String> getResourceIds() {
        return resourceIds.stream().map(UUID::toString).collect(Collectors.toSet());
    }

    @Override
    public void addResourceId(String resourceId) {
        resourceIds.add(StringKeyConverter.UUIDKey.INSTANCE.fromString(resourceId));
    }

    @Override
    public void removeResourceId(String resourceId) {
        resourceIds.remove(StringKeyConverter.UUIDKey.INSTANCE.fromString(resourceId));
    }

    @Override
    public Set<String> getScopeIds() {
        return scopeIds.stream().map(UUID::toString).collect(Collectors.toSet());
    }

    @Override
    public void addScopeId(String scopeId) {
        scopeIds.add(StringKeyConverter.UUIDKey.INSTANCE.fromString(scopeId));
    }

    @Override
    public void removeScopeId(String scopeId) {
        scopeIds.remove(StringKeyConverter.UUIDKey.INSTANCE.fromString(scopeId));
    }

    @Override
    public String getOwner() {
        if (isMetadataInitialized()) return metadata.getOwner();
        return owner;
    }

    @Override
    public void setOwner(String owner) {
        metadata.setOwner(owner);
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof JpaPolicyEntity)) return false;
        return Objects.equals(getId(), ((JpaPolicyEntity) obj).getId());
    }
}
