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

import java.util.Objects;
import java.util.UUID;
import jakarta.persistence.Basic;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
import jakarta.persistence.Version;
import org.hibernate.annotations.Type;
import org.keycloak.models.map.authorization.entity.MapPermissionTicketEntity.AbstractMapPermissionTicketEntity;
import org.keycloak.models.map.common.DeepCloner;
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;


/**
 * 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_permission", uniqueConstraints = {@UniqueConstraint(columnNames = {"realmId", "resourceServerId", "scopeId", "resourceId", "owner", "requester"})})
public class JpaPermissionEntity extends AbstractMapPermissionTicketEntity 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 JpaPermissionMetadata 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 String owner;

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

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

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

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

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

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

    public JpaPermissionEntity(DeepCloner cloner) {
        this.metadata = new JpaPermissionMetadata(cloner);
    }

    /**
     * Used by hibernate when calling cb.construct from read(QueryParameters) method.
     * It is used to select object without metadata(json) field.
     */
    public JpaPermissionEntity(UUID id, int version, Integer entityVersion, String realmId, 
            UUID resourceServerId, String owner, UUID scopeId, UUID policyId, 
            String requester, UUID resourceId) {
        this.id = id;
        this.version = version;
        this.entityVersion = entityVersion;
        this.realmId = realmId;
        this.resourceServerId = resourceServerId;
        this.owner = owner;
        this.scopeId = scopeId;
        this.policyId = policyId;
        this.requester = requester;
        this.resourceId = resourceId;
        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_PERMISSION;
    }

    @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 getOwner() {
        if (isMetadataInitialized()) return metadata.getOwner();
        return owner;
    }

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

    @Override
    public String getRequester() {
        if (isMetadataInitialized()) return metadata.getRequester();
        return requester;
    }

    @Override
    public void setRequester(String requester) {
        metadata.setRequester(requester);
    }

    @Override
    public Long getCreatedTimestamp() {
        return metadata.getCreatedTimestamp();
    }

    @Override
    public void setCreatedTimestamp(Long createdTimestamp) {
        metadata.setCreatedTimestamp(createdTimestamp);
    }

    @Override
    public Long getGrantedTimestamp() {
        return metadata.getGrantedTimestamp();
    }

    @Override
    public void setGrantedTimestamp(Long grantedTimestamp) {
        metadata.setGrantedTimestamp(grantedTimestamp);
    }

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

    @Override
    public void setResourceId(String resourceId) {
        metadata.setResourceId(resourceId);
    }

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

    @Override
    public void setScopeId(String scopeId) {
        metadata.setScopeId(scopeId);
    }

    @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 getPolicyId() {
        if (isMetadataInitialized()) return metadata.getPolicyId();
        return policyId == null ? null : policyId.toString();
    }

    @Override
    public void setPolicyId(String policyId) {
        metadata.setPolicyId(policyId);
    }

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

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