package liman

import (
	

	
	
	
	
	
)

// GetPermissions Gets user and extensions permissons and variables
func ( *models.User,  string) ([]string, map[string]string, error) {
	,  := getRoleMaps()
	if  != nil {
		return nil, nil, 
	}

	 := []string{}
	 := make(map[string]string)
	for ,  := range  {
		, ,  := getPermissionsFromMorph(, strings.ToLower())
		if  != nil {
			return nil, nil, 
		}

		 = append(, ...)

		 = helpers.MergeStringMaps(, )
	}

	return , , nil
}

// GetObjectPermissions Returns object permissions of user
func ( *models.User) ([]string, error) {
	,  := getRoleMaps()
	if  != nil {
		return nil, 
	}

	 := []string{}
	for ,  := range  {
		,  := getObjectPermissionsFromMorph()
		if  != nil {
			return nil, 
		}

		 = append(, ...)
	}

	return , nil
}

// getPermissionsFromMorph Searches db for morph relationships and returns permissions
func getPermissionsFromMorph( string,  string) ([]string, map[string]string, error) {
	 := []*models.Permission{}

	 := database.Connection().Find(&, "morph_id = ?", ).Error
	if  != nil {
		return nil, nil, logger.FiberError(fiber.StatusInternalServerError, "error while fetching the permissions")
	}

	 := []string{}
	 := make(map[string]string)

	for ,  := range  {
		if .Type == "function" {
			if len() > 0 {
				if  == .Value {
					 = append(, .Extra)
				}
			} else {
				 = append(, .Extra)
			}
		}

		if .Type == "variable" {
			[.Key] = .Value
		}
	}

	return , , nil
}

// getObjectPermissionsFromMorph Searches db for morph relationships and returns object permissions
func getObjectPermissionsFromMorph( string) ([]string, error) {
	 := []*models.Permission{}

	 := database.Connection().Find(&, "morph_id = ? AND NOT type = 'function'", ).Error
	if  != nil {
		return nil, 
	}

	 := []string{}
	for ,  := range  {
		 = append(, .Value)
	}

	return , nil
}

// getRoleMaps Retrieves role mapping for users
func getRoleMaps( *models.User) ([]string, error) {
	 := []*models.RoleUsers{}

	 := database.Connection().Find(&, "user_id = ?", .ID).Error
	if  != nil {
		return nil, logger.FiberError(fiber.StatusInternalServerError, "error while fetching the roles")
	}

	 := []string{.ID}
	for ,  := range  {
		 = append(, .RoleID)
	}

	return , nil
}