// Code generated by "gen/generator.go"; DO NOT EDIT.
// In order to regenerate this file execute `go generate` from the repository root.
// More details can be found in the [README](https://github.com/CiscoDevNet/terraform-provider-aci/blob/master/README.md).

package provider

import (
	"context"
	"encoding/json"
	"fmt"

	customTypes "github.com/CiscoDevNet/terraform-provider-aci/v2/internal/custom_types"
	"github.com/CiscoDevNet/terraform-provider-aci/v2/internal/validators"
	"github.com/ciscoecosystem/aci-go-client/v2/client"
	"github.com/ciscoecosystem/aci-go-client/v2/container"
	"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
	"github.com/hashicorp/terraform-plugin-framework/attr"
	"github.com/hashicorp/terraform-plugin-framework/diag"
	"github.com/hashicorp/terraform-plugin-framework/path"
	"github.com/hashicorp/terraform-plugin-framework/resource"
	"github.com/hashicorp/terraform-plugin-framework/resource/schema"
	"github.com/hashicorp/terraform-plugin-framework/resource/schema/objectplanmodifier"
	"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
	"github.com/hashicorp/terraform-plugin-framework/resource/schema/setplanmodifier"
	"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
	"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
	"github.com/hashicorp/terraform-plugin-framework/schema/validator"
	"github.com/hashicorp/terraform-plugin-framework/types"
	"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
	"github.com/hashicorp/terraform-plugin-log/tflog"
)

// Ensure provider defined types fully satisfy framework interfaces.
var _ resource.Resource = &FvApResource{}
var _ resource.ResourceWithImportState = &FvApResource{}

func NewFvApResource() resource.Resource {
	return &FvApResource{}
}

// FvApResource defines the resource implementation.
type FvApResource struct {
	client *client.Client
}

// FvApResourceModel describes the resource data model.
type FvApResourceModel struct {
	Id                     types.String                    `tfsdk:"id"`
	ParentDn               types.String                    `tfsdk:"parent_dn"`
	Annotation             types.String                    `tfsdk:"annotation"`
	Descr                  types.String                    `tfsdk:"description"`
	Name                   types.String                    `tfsdk:"name"`
	NameAlias              types.String                    `tfsdk:"name_alias"`
	OwnerKey               types.String                    `tfsdk:"owner_key"`
	OwnerTag               types.String                    `tfsdk:"owner_tag"`
	Prio                   customTypes.FvApPrioStringValue `tfsdk:"priority"`
	FvRsApMonPol           types.Object                    `tfsdk:"relation_to_monitoring_policy"`
	TagAnnotation          types.Set                       `tfsdk:"annotations"`
	TagTag                 types.Set                       `tfsdk:"tags"`
	DeprecatedParentDn     types.String                    `tfsdk:"tenant_dn"`
	DeprecatedPrio         types.String                    `tfsdk:"prio"`
	DeprecatedFvRsApMonPol types.String                    `tfsdk:"relation_fv_rs_ap_mon_pol"`
}

func getEmptyFvApResourceModel() *FvApResourceModel {
	return &FvApResourceModel{
		Id:         basetypes.NewStringNull(),
		ParentDn:   basetypes.NewStringNull(),
		Annotation: basetypes.NewStringNull(),
		Descr:      basetypes.NewStringNull(),
		Name:       basetypes.NewStringNull(),
		NameAlias:  basetypes.NewStringNull(),
		OwnerKey:   basetypes.NewStringNull(),
		OwnerTag:   basetypes.NewStringNull(),
		Prio:       customTypes.NewFvApPrioStringNull(),
		FvRsApMonPol: types.ObjectNull(map[string]attr.Type{
			"annotation":             types.StringType,
			"monitoring_policy_name": types.StringType,
			"annotations":            types.SetType{ElemType: TagAnnotationFvRsApMonPolFvApType},
			"tags":                   types.SetType{ElemType: TagTagFvRsApMonPolFvApType},
		}),
		TagAnnotation: types.SetNull(types.ObjectType{
			AttrTypes: map[string]attr.Type{
				"key":   types.StringType,
				"value": types.StringType,
			},
		}),
		TagTag: types.SetNull(types.ObjectType{
			AttrTypes: map[string]attr.Type{
				"key":   types.StringType,
				"value": types.StringType,
			},
		}),
		DeprecatedParentDn:     types.String{},
		DeprecatedPrio:         types.String{},
		DeprecatedFvRsApMonPol: types.String{},
	}
}

// FvRsApMonPolFvApResourceModel describes the resource data model for the children without relation ships.
type FvRsApMonPolFvApResourceModel struct {
	Annotation      types.String `tfsdk:"annotation"`
	TnMonEPGPolName types.String `tfsdk:"monitoring_policy_name"`
	TagAnnotation   types.Set    `tfsdk:"annotations"`
	TagTag          types.Set    `tfsdk:"tags"`
}

func getEmptyFvRsApMonPolFvApResourceModel() FvRsApMonPolFvApResourceModel {
	return FvRsApMonPolFvApResourceModel{
		Annotation:      basetypes.NewStringNull(),
		TnMonEPGPolName: basetypes.NewStringNull(),
		TagAnnotation: types.SetNull(types.ObjectType{
			AttrTypes: map[string]attr.Type{
				"key":   types.StringType,
				"value": types.StringType,
			},
		}),
		TagTag: types.SetNull(types.ObjectType{
			AttrTypes: map[string]attr.Type{
				"key":   types.StringType,
				"value": types.StringType,
			},
		}),
	}
}

var FvRsApMonPolFvApType = map[string]attr.Type{
	"annotation":             types.StringType,
	"monitoring_policy_name": types.StringType,
	"annotations":            types.SetType{ElemType: TagAnnotationFvRsApMonPolFvApType},
	"tags":                   types.SetType{ElemType: TagTagFvRsApMonPolFvApType},
}

// TagAnnotationFvRsApMonPolFvApResourceModel describes the resource data model for the children without relation ships.
type TagAnnotationFvRsApMonPolFvApResourceModel struct {
	Key   types.String `tfsdk:"key"`
	Value types.String `tfsdk:"value"`
}

func getEmptyTagAnnotationFvRsApMonPolFvApResourceModel() TagAnnotationFvRsApMonPolFvApResourceModel {
	return TagAnnotationFvRsApMonPolFvApResourceModel{
		Key:   basetypes.NewStringNull(),
		Value: basetypes.NewStringNull(),
	}
}

var TagAnnotationFvRsApMonPolFvApType = types.ObjectType{
	AttrTypes: map[string]attr.Type{
		"key":   types.StringType,
		"value": types.StringType,
	},
}

// TagTagFvRsApMonPolFvApResourceModel describes the resource data model for the children without relation ships.
type TagTagFvRsApMonPolFvApResourceModel struct {
	Key   types.String `tfsdk:"key"`
	Value types.String `tfsdk:"value"`
}

func getEmptyTagTagFvRsApMonPolFvApResourceModel() TagTagFvRsApMonPolFvApResourceModel {
	return TagTagFvRsApMonPolFvApResourceModel{
		Key:   basetypes.NewStringNull(),
		Value: basetypes.NewStringNull(),
	}
}

var TagTagFvRsApMonPolFvApType = types.ObjectType{
	AttrTypes: map[string]attr.Type{
		"key":   types.StringType,
		"value": types.StringType,
	},
}

// TagAnnotationFvApResourceModel describes the resource data model for the children without relation ships.
type TagAnnotationFvApResourceModel struct {
	Key   types.String `tfsdk:"key"`
	Value types.String `tfsdk:"value"`
}

func getEmptyTagAnnotationFvApResourceModel() TagAnnotationFvApResourceModel {
	return TagAnnotationFvApResourceModel{
		Key:   basetypes.NewStringNull(),
		Value: basetypes.NewStringNull(),
	}
}

var TagAnnotationFvApType = types.ObjectType{
	AttrTypes: map[string]attr.Type{
		"key":   types.StringType,
		"value": types.StringType,
	},
}

// TagTagFvApResourceModel describes the resource data model for the children without relation ships.
type TagTagFvApResourceModel struct {
	Key   types.String `tfsdk:"key"`
	Value types.String `tfsdk:"value"`
}

func getEmptyTagTagFvApResourceModel() TagTagFvApResourceModel {
	return TagTagFvApResourceModel{
		Key:   basetypes.NewStringNull(),
		Value: basetypes.NewStringNull(),
	}
}

var TagTagFvApType = types.ObjectType{
	AttrTypes: map[string]attr.Type{
		"key":   types.StringType,
		"value": types.StringType,
	},
}

type FvApIdentifier struct {
	Name types.String
}

type FvApResourceModelV1 struct {
	Annotation   types.String `tfsdk:"annotation"`
	Descr        types.String `tfsdk:"description"`
	Id           types.String `tfsdk:"id"`
	Name         types.String `tfsdk:"name"`
	NameAlias    types.String `tfsdk:"name_alias"`
	ParentDn     types.String `tfsdk:"tenant_dn"`
	Prio         types.String `tfsdk:"prio"`
	FvRsApMonPol types.String `tfsdk:"relation_fv_rs_ap_mon_pol"`
}

func (r *FvApResource) UpgradeState(ctx context.Context) map[int64]resource.StateUpgrader {
	return map[int64]resource.StateUpgrader{
		1: {
			PriorSchema: &schema.Schema{
				Attributes: map[string]schema.Attribute{
					"annotation": schema.StringAttribute{
						Required: false,
						Optional: true,
						Computed: true,
					},
					"description": schema.StringAttribute{
						Required: false,
						Optional: true,
						Computed: true,
					},
					"id": schema.StringAttribute{
						Required: false,
						Optional: true,
						Computed: true,
					},
					"name": schema.StringAttribute{
						Required: true,
						Optional: false,
						Computed: false,
					},
					"name_alias": schema.StringAttribute{
						Required: false,
						Optional: true,
						Computed: true,
					},
					"tenant_dn": schema.StringAttribute{
						Required: true,
						Optional: false,
						Computed: false,
					},
					"prio": schema.StringAttribute{
						Required: false,
						Optional: true,
						Computed: true,
					},
					"relation_fv_rs_ap_mon_pol": schema.StringAttribute{
						Required: false,
						Optional: true,
						Computed: true,
					},
				},
				Blocks: map[string]schema.Block{},
			},
			StateUpgrader: func(ctx context.Context, req resource.UpgradeStateRequest, resp *resource.UpgradeStateResponse) {
				var priorStateData FvApResourceModelV1

				resp.Diagnostics.Append(req.State.Get(ctx, &priorStateData)...)

				if resp.Diagnostics.HasError() {
					return
				}

				upgradedStateData := FvApResourceModel{
					Id:                     priorStateData.Id,
					ParentDn:               priorStateData.ParentDn,
					Annotation:             priorStateData.Annotation,
					Descr:                  priorStateData.Descr,
					Name:                   priorStateData.Name,
					NameAlias:              priorStateData.NameAlias,
					OwnerKey:               basetypes.NewStringNull(),
					OwnerTag:               basetypes.NewStringNull(),
					Prio:                   customTypes.FvApPrioStringValue{StringValue: priorStateData.Prio},
					DeprecatedParentDn:     priorStateData.ParentDn,
					DeprecatedPrio:         priorStateData.Prio,
					DeprecatedFvRsApMonPol: priorStateData.FvRsApMonPol,
				}

				FvRsApMonPolObject := FvRsApMonPolFvApResourceModel{
					Annotation:      basetypes.NewStringNull(),
					TnMonEPGPolName: basetypes.NewStringValue(GetMOName(priorStateData.FvRsApMonPol.ValueString())),
					TagAnnotation: basetypes.NewSetNull(types.ObjectType{
						AttrTypes: map[string]attr.Type{
							"key":   types.StringType,
							"value": types.StringType,
						},
					}),
					TagTag: basetypes.NewSetNull(types.ObjectType{
						AttrTypes: map[string]attr.Type{
							"key":   types.StringType,
							"value": types.StringType,
						},
					}),
				}
				fvRsApMonPolObject, _ := types.ObjectValueFrom(ctx, FvRsApMonPolFvApType, FvRsApMonPolObject)
				upgradedStateData.FvRsApMonPol = fvRsApMonPolObject

				upgradedStateData.TagAnnotation = types.SetNull(
					types.ObjectType{
						AttrTypes: map[string]attr.Type{
							"key":   basetypes.StringType{},
							"value": basetypes.StringType{},
						},
					},
				)

				upgradedStateData.TagTag = types.SetNull(
					types.ObjectType{
						AttrTypes: map[string]attr.Type{
							"key":   basetypes.StringType{},
							"value": basetypes.StringType{},
						},
					},
				)

				resp.Diagnostics.Append(resp.State.Set(ctx, upgradedStateData)...)
			},
		},
	}
}

func setFvApLegacyAttributes(ctx context.Context, diags *diag.Diagnostics, data, staticData *FvApResourceModel, classReadInfo []interface{}) {
	data.DeprecatedParentDn = data.ParentDn
	attributes := classReadInfo[0].(map[string]interface{})["attributes"].(map[string]interface{})
	for attributeName, attributeValue := range attributes {
		if attributeName == "prio" {
			data.DeprecatedPrio = basetypes.NewStringValue(attributeValue.(string))
		}
	}
	data.DeprecatedFvRsApMonPol = basetypes.NewStringNull()

	_, ok := classReadInfo[0].(map[string]interface{})["children"]
	if ok {
		children := classReadInfo[0].(map[string]interface{})["children"].([]interface{})
		for _, child := range children {
			for childClassName, childClassDetails := range child.(map[string]interface{}) {
				childAttributes := childClassDetails.(map[string]interface{})["attributes"].(map[string]interface{})
				if childClassName == "fvRsApMonPol" {
					for childAttributeName, childAttributeValue := range childAttributes {
						if childAttributeName == "tDn" {
							data.DeprecatedFvRsApMonPol = basetypes.NewStringValue(childAttributeValue.(string))
						}
					}
				}
			}
		}
	}
}

func (r *FvApResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) {
	if !req.Plan.Raw.IsNull() {
		var planData, stateData, configData *FvApResourceModel
		resp.Diagnostics.Append(req.Plan.Get(ctx, &planData)...)
		resp.Diagnostics.Append(req.State.Get(ctx, &stateData)...)
		resp.Diagnostics.Append(req.Config.Get(ctx, &configData)...)

		if resp.Diagnostics.HasError() {
			return
		}

		if (planData.Id.IsUnknown() || planData.Id.IsNull()) && !planData.ParentDn.IsUnknown() && !planData.Name.IsUnknown() {
			setFvApId(ctx, planData)
		}

		if stateData == nil && !globalAllowExistingOnCreate && !planData.Id.IsUnknown() && !planData.Id.IsNull() {
			CheckDn(ctx, &resp.Diagnostics, r.client, "fvAp", planData.Id.ValueString())
			if resp.Diagnostics.HasError() {
				return
			}
		}
		if !configData.FvRsApMonPol.IsNull() && stateData != nil {
			if IsEmptySingleNestedAttribute(configData.FvRsApMonPol.Attributes()) {
				FvRsApMonPolObject, _ := types.ObjectValueFrom(ctx, FvRsApMonPolFvApType, getEmptyFvRsApMonPolFvApResourceModel())
				planData.FvRsApMonPol = FvRsApMonPolObject
			}
		}

		if !configData.DeprecatedParentDn.IsNull() {
			planData.ParentDn = configData.DeprecatedParentDn
		}

		if !configData.DeprecatedPrio.IsNull() {
			planData.Prio = customTypes.FvApPrioStringValue{StringValue: configData.DeprecatedPrio}
		}

		if !configData.DeprecatedFvRsApMonPol.IsNull() {
			var newAttributeValues FvRsApMonPolFvApResourceModel
			tagAnnotationFvRsApMonPolFvApValue, _ := types.SetValueFrom(ctx, TagAnnotationFvRsApMonPolFvApType, make([]TagAnnotationFvRsApMonPolFvApResourceModel, 0))
			tagTagFvRsApMonPolFvApValue, _ := types.SetValueFrom(ctx, TagTagFvRsApMonPolFvApType, make([]TagTagFvRsApMonPolFvApResourceModel, 0))
			annotationValue := planData.Annotation
			if stateData != nil && !IsEmptySingleNestedAttribute(stateData.FvRsApMonPol.Attributes()) {
				stateData.FvRsApMonPol.As(ctx, &newAttributeValues, basetypes.ObjectAsOptions{})
				annotationValue = newAttributeValues.Annotation
				tagAnnotationFvRsApMonPolFvApValue = newAttributeValues.TagAnnotation
				tagTagFvRsApMonPolFvApValue = newAttributeValues.TagTag
			}
			tnMonEPGPolNameValue := basetypes.NewStringUnknown()
			if !configData.DeprecatedFvRsApMonPol.IsUnknown() {
				tnMonEPGPolNameValue = basetypes.NewStringValue(GetMOName(configData.DeprecatedFvRsApMonPol.ValueString()))
			}
			FvRsApMonPol := FvRsApMonPolFvApResourceModel{
				Annotation:      annotationValue,
				TnMonEPGPolName: tnMonEPGPolNameValue,
				TagAnnotation:   tagAnnotationFvRsApMonPolFvApValue,
				TagTag:          tagTagFvRsApMonPolFvApValue,
			}
			FvRsApMonPolObject, _ := types.ObjectValueFrom(ctx, FvRsApMonPolFvApType, FvRsApMonPol)
			planData.FvRsApMonPol = FvRsApMonPolObject
		}

		// Workaround to compare the state with plan to avoid plan changes with only known after apply
		if stateData != nil {
			avoidFvApPlanChangeForKnownAfterApplyOnly(ctx, planData, stateData, configData)
		}

		resp.Diagnostics.Append(resp.Plan.Set(ctx, &planData)...)
	}
}

func avoidFvApPlanChangeForKnownAfterApplyOnly(ctx context.Context, planData, stateData, configData *FvApResourceModel) {
	// Set read-only and deprecated attributes in planData from stateData
	if configData.DeprecatedParentDn.IsNull() {
		planData.DeprecatedParentDn = stateData.DeprecatedParentDn
	}
	if configData.DeprecatedPrio.IsNull() {
		planData.DeprecatedPrio = stateData.DeprecatedPrio
	}
	if configData.DeprecatedFvRsApMonPol.IsNull() {
		planData.DeprecatedFvRsApMonPol = stateData.DeprecatedFvRsApMonPol
	}

	// Compare the string representation of the planData and stateData because structs cannot be compared directly
	if fmt.Sprintf("%s", planData) != fmt.Sprintf("%s", stateData) {
		if configData.DeprecatedParentDn.IsNull() {
			planData.DeprecatedParentDn = basetypes.NewStringUnknown()
		}
		if configData.DeprecatedPrio.IsNull() {
			planData.DeprecatedPrio = basetypes.NewStringUnknown()
		}
		if configData.DeprecatedFvRsApMonPol.IsNull() {
			planData.DeprecatedFvRsApMonPol = basetypes.NewStringUnknown()
		}
	}
}

func (r *FvApResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
	tflog.Debug(ctx, "Start metadata of resource: aci_application_profile")
	resp.TypeName = req.ProviderTypeName + "_application_profile"
	tflog.Debug(ctx, "End metadata of resource: aci_application_profile")
}

func (r *FvApResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
	tflog.Debug(ctx, "Start schema of resource: aci_application_profile")
	resp.Schema = schema.Schema{
		// This description is used by the documentation generator and the language server.
		MarkdownDescription: "The application_profile resource for the 'fvAp' class",
		Version:             2,

		Attributes: map[string]schema.Attribute{
			// Deprecated attributes
			"tenant_dn": schema.StringAttribute{
				Optional:           true,
				Computed:           true,
				DeprecationMessage: "Attribute 'tenant_dn' is deprecated, please refer to 'parent_dn' instead. The attribute will be removed in the next major version of the provider.",
				Validators: []validator.String{
					stringvalidator.ConflictsWith(path.Expressions{
						path.MatchRoot("parent_dn"),
					}...),
				},
			},
			"prio": schema.StringAttribute{
				Optional:           true,
				Computed:           true,
				DeprecationMessage: "Attribute 'prio' is deprecated, please refer to 'priority' instead. The attribute will be removed in the next major version of the provider.",
				Validators: []validator.String{
					stringvalidator.ConflictsWith(path.Expressions{
						path.MatchRoot("priority"),
					}...),
				},
			},
			"relation_fv_rs_ap_mon_pol": schema.StringAttribute{
				Optional:           true,
				Computed:           true,
				DeprecationMessage: "Attribute 'relation_fv_rs_ap_mon_pol' is deprecated, please refer to 'relation_to_monitoring_policy' instead. The attribute will be removed in the next major version of the provider.",
				Validators: []validator.String{
					stringvalidator.ConflictsWith(path.Expressions{
						path.MatchRoot("relation_to_monitoring_policy"),
					}...),
				},
			},
			// End of deprecated attributes
			"id": schema.StringAttribute{
				Computed:            true,
				MarkdownDescription: "The distinguished name (DN) of the Application Profile object.",
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
				},
			},
			"parent_dn": schema.StringAttribute{
				Optional:            true,
				Computed:            true,
				MarkdownDescription: "The distinguished name (DN) of the parent object.",
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
					stringplanmodifier.RequiresReplace(),
				},
				Validators: []validator.String{
					stringvalidator.AtLeastOneOf(path.Expressions{
						path.MatchRoot("tenant_dn"),
					}...),
				},
			},
			"annotation": schema.StringAttribute{
				Optional: true,
				Computed: true,
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
					SetToStringNullWhenStateIsNullPlanIsUnknownDuringUpdate(),
				},
				Default:             stringdefault.StaticString(globalAnnotation),
				MarkdownDescription: `The annotation of the Application Profile object.`,
			},
			"description": schema.StringAttribute{
				Optional: true,
				Computed: true,
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
					SetToStringNullWhenStateIsNullPlanIsUnknownDuringUpdate(),
				},
				MarkdownDescription: `The description of the Application Profile object.`,
			},
			"name": schema.StringAttribute{
				Required: true,
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
					SetToStringNullWhenStateIsNullPlanIsUnknownDuringUpdate(),
					stringplanmodifier.RequiresReplace(),
				},
				MarkdownDescription: `The name of the Application Profile object.`,
			},
			"name_alias": schema.StringAttribute{
				Optional: true,
				Computed: true,
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
					SetToStringNullWhenStateIsNullPlanIsUnknownDuringUpdate(),
				},
				MarkdownDescription: `The name alias of the Application Profile object.`,
			},
			"owner_key": schema.StringAttribute{
				Optional: true,
				Computed: true,
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
					SetToStringNullWhenStateIsNullPlanIsUnknownDuringUpdate(),
				},
				MarkdownDescription: `The key for enabling clients to own their data for entity correlation.`,
			},
			"owner_tag": schema.StringAttribute{
				Optional: true,
				Computed: true,
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
					SetToStringNullWhenStateIsNullPlanIsUnknownDuringUpdate(),
				},
				MarkdownDescription: `A tag for enabling clients to add their own data. For example, to indicate who created this object.`,
			},
			"priority": schema.StringAttribute{
				CustomType: customTypes.FvApPrioStringType{},
				Optional:   true,
				Computed:   true,
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
					SetToStringNullWhenStateIsNullPlanIsUnknownDuringUpdate(),
				},
				Validators: []validator.String{
					stringvalidator.Any(
						stringvalidator.OneOf("level1", "level2", "level3", "level4", "level5", "level6", "unspecified"),
						validators.InBetweenFromString(0, 9),
					),
				},
				MarkdownDescription: `The Quality of Service (QoS) priority class ID. QoS refers to the capability of a network to provide better service to selected network traffic over various technologies. The primary goal of QoS is to provide priority including dedicated bandwidth, controlled jitter and latency (required by some real-time and interactive traffic), and improved loss characteristics. You can configure the bandwidth of each QoS level using QoS profiles.`,
			},
			"relation_to_monitoring_policy": schema.SingleNestedAttribute{
				MarkdownDescription: `A source relation to the monitoring policy model for the endpoint group semantic scope. This is an internal object.`,
				Optional:            true,
				Computed:            true,
				PlanModifiers: []planmodifier.Object{
					objectplanmodifier.UseStateForUnknown(),
				},
				Attributes: map[string]schema.Attribute{
					"annotation": schema.StringAttribute{
						Optional: true,
						Computed: true,
						PlanModifiers: []planmodifier.String{
							stringplanmodifier.UseStateForUnknown(),
						},
						MarkdownDescription: `The annotation of the Relation From Application Profile To Monitoring Policy object.`,
					},
					"monitoring_policy_name": schema.StringAttribute{
						Optional: true,
						Computed: true,
						PlanModifiers: []planmodifier.String{
							stringplanmodifier.UseStateForUnknown(),
						},
						MarkdownDescription: `The name of the monitoring policy.`,
					},
					"annotations": schema.SetNestedAttribute{
						MarkdownDescription: ``,
						Optional:            true,
						Computed:            true,
						PlanModifiers: []planmodifier.Set{
							setplanmodifier.UseStateForUnknown(),
						},
						NestedObject: schema.NestedAttributeObject{
							Attributes: map[string]schema.Attribute{
								"key": schema.StringAttribute{
									Required: true,
									PlanModifiers: []planmodifier.String{
										stringplanmodifier.UseStateForUnknown(),
									},
									MarkdownDescription: `The key used to uniquely identify this configuration object.`,
								},
								"value": schema.StringAttribute{
									Required: true,
									PlanModifiers: []planmodifier.String{
										stringplanmodifier.UseStateForUnknown(),
									},
									MarkdownDescription: `The value of the property.`,
								},
							},
						},
					},
					"tags": schema.SetNestedAttribute{
						MarkdownDescription: ``,
						Optional:            true,
						Computed:            true,
						PlanModifiers: []planmodifier.Set{
							setplanmodifier.UseStateForUnknown(),
						},
						NestedObject: schema.NestedAttributeObject{
							Attributes: map[string]schema.Attribute{
								"key": schema.StringAttribute{
									Required: true,
									PlanModifiers: []planmodifier.String{
										stringplanmodifier.UseStateForUnknown(),
									},
									MarkdownDescription: `The key used to uniquely identify this configuration object.`,
								},
								"value": schema.StringAttribute{
									Required: true,
									PlanModifiers: []planmodifier.String{
										stringplanmodifier.UseStateForUnknown(),
									},
									MarkdownDescription: `The value of the property.`,
								},
							},
						},
					},
				},
			},
			"annotations": schema.SetNestedAttribute{
				MarkdownDescription: ``,
				Optional:            true,
				Computed:            true,
				PlanModifiers: []planmodifier.Set{
					setplanmodifier.UseStateForUnknown(),
				},
				NestedObject: schema.NestedAttributeObject{
					Attributes: map[string]schema.Attribute{
						"key": schema.StringAttribute{
							Required: true,
							PlanModifiers: []planmodifier.String{
								stringplanmodifier.UseStateForUnknown(),
							},
							MarkdownDescription: `The key used to uniquely identify this configuration object.`,
						},
						"value": schema.StringAttribute{
							Required: true,
							PlanModifiers: []planmodifier.String{
								stringplanmodifier.UseStateForUnknown(),
							},
							MarkdownDescription: `The value of the property.`,
						},
					},
				},
			},
			"tags": schema.SetNestedAttribute{
				MarkdownDescription: ``,
				Optional:            true,
				Computed:            true,
				PlanModifiers: []planmodifier.Set{
					setplanmodifier.UseStateForUnknown(),
				},
				NestedObject: schema.NestedAttributeObject{
					Attributes: map[string]schema.Attribute{
						"key": schema.StringAttribute{
							Required: true,
							PlanModifiers: []planmodifier.String{
								stringplanmodifier.UseStateForUnknown(),
							},
							MarkdownDescription: `The key used to uniquely identify this configuration object.`,
						},
						"value": schema.StringAttribute{
							Required: true,
							PlanModifiers: []planmodifier.String{
								stringplanmodifier.UseStateForUnknown(),
							},
							MarkdownDescription: `The value of the property.`,
						},
					},
				},
			},
		},
		Blocks: map[string]schema.Block{},
	}
	tflog.Debug(ctx, "End schema of resource: aci_application_profile")
}

func (r *FvApResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
	tflog.Debug(ctx, "Start configure of resource: aci_application_profile")
	// Prevent panic if the provider has not been configured.
	if req.ProviderData == nil {
		return
	}

	client, ok := req.ProviderData.(*client.Client)

	if !ok {
		resp.Diagnostics.AddError(
			"Unexpected Resource Configure Type",
			fmt.Sprintf("Expected *client.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
		)

		return
	}

	r.client = client
	tflog.Debug(ctx, "End configure of resource: aci_application_profile")
}

func (r *FvApResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
	tflog.Debug(ctx, "Start create of resource: aci_application_profile")
	// On create retrieve information on current state prior to making any changes in order to determine child delete operations
	var stateData *FvApResourceModel
	resp.Diagnostics.Append(req.Plan.Get(ctx, &stateData)...)
	if stateData.Id.IsUnknown() || stateData.Id.IsNull() {
		setFvApId(ctx, stateData)
	}
	getAndSetFvApAttributes(ctx, &resp.Diagnostics, r.client, stateData)
	if !globalAllowExistingOnCreate && !stateData.Id.IsNull() {
		resp.Diagnostics.AddError(
			"Object Already Exists",
			fmt.Sprintf("The fvAp object with DN '%s' already exists.", stateData.Id.ValueString()),
		)
		return
	}

	var data *FvApResourceModel

	// Read Terraform plan data into the model
	resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)

	if resp.Diagnostics.HasError() {
		return
	}

	if data.Id.IsUnknown() || data.Id.IsNull() {
		setFvApId(ctx, data)
	}

	tflog.Debug(ctx, fmt.Sprintf("Create of resource aci_application_profile with id '%s'", data.Id.ValueString()))

	var fvRsApMonPolPlan, fvRsApMonPolState FvRsApMonPolFvApResourceModel
	data.FvRsApMonPol.As(ctx, &fvRsApMonPolPlan, basetypes.ObjectAsOptions{})
	stateData.FvRsApMonPol.As(ctx, &fvRsApMonPolState, basetypes.ObjectAsOptions{})
	var tagAnnotationPlan, tagAnnotationState []TagAnnotationFvApResourceModel
	data.TagAnnotation.ElementsAs(ctx, &tagAnnotationPlan, false)
	stateData.TagAnnotation.ElementsAs(ctx, &tagAnnotationState, false)
	var tagTagPlan, tagTagState []TagTagFvApResourceModel
	data.TagTag.ElementsAs(ctx, &tagTagPlan, false)
	stateData.TagTag.ElementsAs(ctx, &tagTagState, false)
	jsonPayload := getFvApCreateJsonPayload(ctx, &resp.Diagnostics, true, data, fvRsApMonPolPlan, fvRsApMonPolState, tagAnnotationPlan, tagAnnotationState, tagTagPlan, tagTagState)

	if resp.Diagnostics.HasError() {
		return
	}

	DoRestRequest(ctx, &resp.Diagnostics, r.client, fmt.Sprintf("api/mo/%s.json", data.Id.ValueString()), "POST", jsonPayload)

	if resp.Diagnostics.HasError() {
		return
	}

	getAndSetFvApAttributes(ctx, &resp.Diagnostics, r.client, data)

	// Save data into Terraform state
	resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
	tflog.Debug(ctx, fmt.Sprintf("End create of resource aci_application_profile with id '%s'", data.Id.ValueString()))
}

func (r *FvApResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	tflog.Debug(ctx, "Start read of resource: aci_application_profile")
	var data *FvApResourceModel

	// Read Terraform prior state data into the model
	resp.Diagnostics.Append(req.State.Get(ctx, &data)...)

	if resp.Diagnostics.HasError() {
		return
	}

	tflog.Debug(ctx, fmt.Sprintf("Read of resource aci_application_profile with id '%s'", data.Id.ValueString()))

	getAndSetFvApAttributes(ctx, &resp.Diagnostics, r.client, data)

	// Save updated data into Terraform state
	if data.Id.IsNull() {
		var emptyData *FvApResourceModel
		resp.Diagnostics.Append(resp.State.Set(ctx, &emptyData)...)
	} else {
		resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
	}

	tflog.Debug(ctx, fmt.Sprintf("End read of resource aci_application_profile with id '%s'", data.Id.ValueString()))
}

func (r *FvApResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
	tflog.Debug(ctx, "Start update of resource: aci_application_profile")
	var data *FvApResourceModel
	var stateData *FvApResourceModel

	// Read Terraform plan data into the model
	resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
	resp.Diagnostics.Append(req.State.Get(ctx, &stateData)...)

	if resp.Diagnostics.HasError() {
		return
	}

	tflog.Debug(ctx, fmt.Sprintf("Update of resource aci_application_profile with id '%s'", data.Id.ValueString()))

	var fvRsApMonPolPlan, fvRsApMonPolState FvRsApMonPolFvApResourceModel
	data.FvRsApMonPol.As(ctx, &fvRsApMonPolPlan, basetypes.ObjectAsOptions{})
	stateData.FvRsApMonPol.As(ctx, &fvRsApMonPolState, basetypes.ObjectAsOptions{})
	var tagAnnotationPlan, tagAnnotationState []TagAnnotationFvApResourceModel
	data.TagAnnotation.ElementsAs(ctx, &tagAnnotationPlan, false)
	stateData.TagAnnotation.ElementsAs(ctx, &tagAnnotationState, false)
	var tagTagPlan, tagTagState []TagTagFvApResourceModel
	data.TagTag.ElementsAs(ctx, &tagTagPlan, false)
	stateData.TagTag.ElementsAs(ctx, &tagTagState, false)
	jsonPayload := getFvApCreateJsonPayload(ctx, &resp.Diagnostics, false, data, fvRsApMonPolPlan, fvRsApMonPolState, tagAnnotationPlan, tagAnnotationState, tagTagPlan, tagTagState)

	if resp.Diagnostics.HasError() {
		return
	}

	DoRestRequest(ctx, &resp.Diagnostics, r.client, fmt.Sprintf("api/mo/%s.json", data.Id.ValueString()), "POST", jsonPayload)

	if resp.Diagnostics.HasError() {
		return
	}

	getAndSetFvApAttributes(ctx, &resp.Diagnostics, r.client, data)

	// Save updated data into Terraform state
	resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
	tflog.Debug(ctx, fmt.Sprintf("End update of resource aci_application_profile with id '%s'", data.Id.ValueString()))
}

func (r *FvApResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	tflog.Debug(ctx, "Start delete of resource: aci_application_profile")
	var data *FvApResourceModel

	// Read Terraform prior state data into the model
	resp.Diagnostics.Append(req.State.Get(ctx, &data)...)

	if resp.Diagnostics.HasError() {
		return
	}

	tflog.Debug(ctx, fmt.Sprintf("Delete of resource aci_application_profile with id '%s'", data.Id.ValueString()))
	jsonPayload := GetDeleteJsonPayload(ctx, &resp.Diagnostics, "fvAp", data.Id.ValueString())
	if resp.Diagnostics.HasError() {
		return
	}
	DoRestRequest(ctx, &resp.Diagnostics, r.client, fmt.Sprintf("api/mo/%s.json", data.Id.ValueString()), "POST", jsonPayload)
	if resp.Diagnostics.HasError() {
		return
	}
	tflog.Debug(ctx, fmt.Sprintf("End delete of resource aci_application_profile with id '%s'", data.Id.ValueString()))
}

func (r *FvApResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
	tflog.Debug(ctx, "Start import state of resource: aci_application_profile")
	resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)

	var stateData *FvApResourceModel
	resp.Diagnostics.Append(resp.State.Get(ctx, &stateData)...)
	tflog.Debug(ctx, fmt.Sprintf("Import state of resource aci_application_profile with id '%s'", stateData.Id.ValueString()))

	tflog.Debug(ctx, "End import of state resource: aci_application_profile")
}

func getAndSetFvApAttributes(ctx context.Context, diags *diag.Diagnostics, client *client.Client, data *FvApResourceModel) {
	requestData := DoRestRequest(ctx, diags, client, fmt.Sprintf("api/mo/%s.json?rsp-subtree=full&rsp-subtree-class=%s", data.Id.ValueString(), "fvAp,fvRsApMonPol,tagAnnotation,tagTag,tagAnnotation,tagTag"), "GET", nil)

	readData := getEmptyFvApResourceModel()

	if diags.HasError() {
		return
	}
	if requestData.Search("imdata").Search("fvAp").Data() != nil {
		classReadInfo := requestData.Search("imdata").Search("fvAp").Data().([]interface{})
		if len(classReadInfo) == 1 {
			attributes := classReadInfo[0].(map[string]interface{})["attributes"].(map[string]interface{})
			for attributeName, attributeValue := range attributes {
				if attributeName == "dn" {
					readData.Id = basetypes.NewStringValue(attributeValue.(string))
					setFvApParentDn(ctx, attributeValue.(string), readData)
				}
				if attributeName == "annotation" {
					readData.Annotation = basetypes.NewStringValue(attributeValue.(string))
				}
				if attributeName == "descr" {
					readData.Descr = basetypes.NewStringValue(attributeValue.(string))
				}
				if attributeName == "name" {
					readData.Name = basetypes.NewStringValue(attributeValue.(string))
				}
				if attributeName == "nameAlias" {
					readData.NameAlias = basetypes.NewStringValue(attributeValue.(string))
				}
				if attributeName == "ownerKey" {
					readData.OwnerKey = basetypes.NewStringValue(attributeValue.(string))
				}
				if attributeName == "ownerTag" {
					readData.OwnerTag = basetypes.NewStringValue(attributeValue.(string))
				}
				if attributeName == "prio" {
					readData.Prio = customTypes.NewFvApPrioStringValue(attributeValue.(string))
				}
			}
			FvRsApMonPolFvApList := make([]FvRsApMonPolFvApResourceModel, 0)
			TagAnnotationFvApList := make([]TagAnnotationFvApResourceModel, 0)
			TagTagFvApList := make([]TagTagFvApResourceModel, 0)
			_, ok := classReadInfo[0].(map[string]interface{})["children"]
			if ok {
				children := classReadInfo[0].(map[string]interface{})["children"].([]interface{})
				for _, child := range children {
					for childClassName, childClassDetails := range child.(map[string]interface{}) {
						childAttributes := childClassDetails.(map[string]interface{})["attributes"].(map[string]interface{})
						if childClassName == "fvRsApMonPol" {
							FvRsApMonPolFvAp := getEmptyFvRsApMonPolFvApResourceModel()
							for childAttributeName, childAttributeValue := range childAttributes {
								if childAttributeName == "annotation" {
									FvRsApMonPolFvAp.Annotation = basetypes.NewStringValue(childAttributeValue.(string))
								}
								if childAttributeName == "tnMonEPGPolName" {
									FvRsApMonPolFvAp.TnMonEPGPolName = basetypes.NewStringValue(childAttributeValue.(string))
								}

							}
							TagAnnotationFvRsApMonPolFvApList := make([]TagAnnotationFvRsApMonPolFvApResourceModel, 0)
							TagTagFvRsApMonPolFvApList := make([]TagTagFvRsApMonPolFvApResourceModel, 0)
							childrenOfFvRsApMonPolFvAp, childrenOfFvRsApMonPolFvApExist := childClassDetails.(map[string]interface{})["children"]
							if childrenOfFvRsApMonPolFvApExist {
								for _, childFvRsApMonPolFvAp := range childrenOfFvRsApMonPolFvAp.([]interface{}) {
									for childClassNameFvRsApMonPolFvAp, childClassDetailsFvRsApMonPolFvAp := range childFvRsApMonPolFvAp.(map[string]interface{}) {
										if childClassNameFvRsApMonPolFvAp == "tagAnnotation" {
											TagAnnotationFvRsApMonPolFvAp := getEmptyTagAnnotationFvRsApMonPolFvApResourceModel()
											tagAnnotationchildAttributeValue := childClassDetailsFvRsApMonPolFvAp.(map[string]interface{})["attributes"].(map[string]interface{})
											for childAttributeName, childAttributeValue := range tagAnnotationchildAttributeValue {
												if childAttributeName == "key" {
													TagAnnotationFvRsApMonPolFvAp.Key = basetypes.NewStringValue(childAttributeValue.(string))
												}
												if childAttributeName == "value" {
													TagAnnotationFvRsApMonPolFvAp.Value = basetypes.NewStringValue(childAttributeValue.(string))
												}
											}
											TagAnnotationFvRsApMonPolFvApList = append(TagAnnotationFvRsApMonPolFvApList, TagAnnotationFvRsApMonPolFvAp)
										}
										if childClassNameFvRsApMonPolFvAp == "tagTag" {
											TagTagFvRsApMonPolFvAp := getEmptyTagTagFvRsApMonPolFvApResourceModel()
											tagTagchildAttributeValue := childClassDetailsFvRsApMonPolFvAp.(map[string]interface{})["attributes"].(map[string]interface{})
											for childAttributeName, childAttributeValue := range tagTagchildAttributeValue {
												if childAttributeName == "key" {
													TagTagFvRsApMonPolFvAp.Key = basetypes.NewStringValue(childAttributeValue.(string))
												}
												if childAttributeName == "value" {
													TagTagFvRsApMonPolFvAp.Value = basetypes.NewStringValue(childAttributeValue.(string))
												}
											}
											TagTagFvRsApMonPolFvApList = append(TagTagFvRsApMonPolFvApList, TagTagFvRsApMonPolFvAp)
										}
									}
								}
							}
							TagAnnotationFvRsApMonPolFvApSet, _ := types.SetValueFrom(ctx, TagAnnotationFvRsApMonPolFvApType, TagAnnotationFvRsApMonPolFvApList)
							FvRsApMonPolFvAp.TagAnnotation = TagAnnotationFvRsApMonPolFvApSet
							TagTagFvRsApMonPolFvApSet, _ := types.SetValueFrom(ctx, TagTagFvRsApMonPolFvApType, TagTagFvRsApMonPolFvApList)
							FvRsApMonPolFvAp.TagTag = TagTagFvRsApMonPolFvApSet
							FvRsApMonPolFvApList = append(FvRsApMonPolFvApList, FvRsApMonPolFvAp)
						}
						if childClassName == "tagAnnotation" {
							TagAnnotationFvAp := getEmptyTagAnnotationFvApResourceModel()
							for childAttributeName, childAttributeValue := range childAttributes {
								if childAttributeName == "key" {
									TagAnnotationFvAp.Key = basetypes.NewStringValue(childAttributeValue.(string))
								}
								if childAttributeName == "value" {
									TagAnnotationFvAp.Value = basetypes.NewStringValue(childAttributeValue.(string))
								}

							}
							TagAnnotationFvApList = append(TagAnnotationFvApList, TagAnnotationFvAp)
						}
						if childClassName == "tagTag" {
							TagTagFvAp := getEmptyTagTagFvApResourceModel()
							for childAttributeName, childAttributeValue := range childAttributes {
								if childAttributeName == "key" {
									TagTagFvAp.Key = basetypes.NewStringValue(childAttributeValue.(string))
								}
								if childAttributeName == "value" {
									TagTagFvAp.Value = basetypes.NewStringValue(childAttributeValue.(string))
								}

							}
							TagTagFvApList = append(TagTagFvApList, TagTagFvAp)
						}
					}
				}
			}
			if len(FvRsApMonPolFvApList) == 1 {
				fvRsApMonPolObject, _ := types.ObjectValueFrom(ctx, FvRsApMonPolFvApType, FvRsApMonPolFvApList[0])
				readData.FvRsApMonPol = fvRsApMonPolObject
			} else {
				fvRsApMonPolObject, _ := types.ObjectValueFrom(ctx, FvRsApMonPolFvApType, getEmptyFvRsApMonPolFvApResourceModel())
				readData.FvRsApMonPol = fvRsApMonPolObject
			}
			tagAnnotationSet, _ := types.SetValueFrom(ctx, readData.TagAnnotation.ElementType(ctx), TagAnnotationFvApList)
			readData.TagAnnotation = tagAnnotationSet
			tagTagSet, _ := types.SetValueFrom(ctx, readData.TagTag.ElementType(ctx), TagTagFvApList)
			readData.TagTag = tagTagSet
			setFvApLegacyAttributes(ctx, diags, readData, data, classReadInfo)
		} else {
			diags.AddError(
				"too many results in response",
				fmt.Sprintf("%v matches returned for class 'fvAp'. Please report this issue to the provider developers.", len(classReadInfo)),
			)
		}
	} else {
		readData.Id = basetypes.NewStringNull()
	}
	*data = *readData
}

func getFvApRn(ctx context.Context, data *FvApResourceModel) string {
	return fmt.Sprintf("ap-%s", data.Name.ValueString())
}

func setFvApParentDn(ctx context.Context, dn string, data *FvApResourceModel) {
	bracketIndex := 0
	rnIndex := 0
	for i := len(dn) - 1; i >= 0; i-- {
		if string(dn[i]) == "]" {
			bracketIndex = bracketIndex + 1
		} else if string(dn[i]) == "[" {
			bracketIndex = bracketIndex - 1
		} else if string(dn[i]) == "/" && bracketIndex == 0 {
			rnIndex = i
			break
		}
	}
	data.ParentDn = basetypes.NewStringValue(dn[:rnIndex])
}

func setFvApId(ctx context.Context, data *FvApResourceModel) {
	rn := getFvApRn(ctx, data)
	data.Id = types.StringValue(fmt.Sprintf("%s/%s", data.ParentDn.ValueString(), rn))
}

func getFvApFvRsApMonPolChildPayloads(ctx context.Context, diags *diag.Diagnostics, data *FvApResourceModel, fvRsApMonPolFvApPlan, fvRsApMonPolFvApState FvRsApMonPolFvApResourceModel) []map[string]interface{} {
	childPayloads := []map[string]interface{}{}
	if !data.FvRsApMonPol.IsNull() && !data.FvRsApMonPol.IsUnknown() {
		FvRsApMonPolFvApChildren := make([]map[string]interface{}, 0)
		childMap := NewAciObject()
		if !IsEmptySingleNestedAttribute(data.FvRsApMonPol.Attributes()) {
			if !fvRsApMonPolFvApPlan.Annotation.IsUnknown() && !fvRsApMonPolFvApPlan.Annotation.IsNull() {
				childMap.Attributes["annotation"] = fvRsApMonPolFvApPlan.Annotation.ValueString()
			} else {
				childMap.Attributes["annotation"] = globalAnnotation
			}
			if !fvRsApMonPolFvApPlan.TnMonEPGPolName.IsUnknown() && !fvRsApMonPolFvApPlan.TnMonEPGPolName.IsNull() {
				childMap.Attributes["tnMonEPGPolName"] = fvRsApMonPolFvApPlan.TnMonEPGPolName.ValueString()
			}

			var tagAnnotationFvRsApMonPolFvApPlan, tagAnnotationFvRsApMonPolFvApState []TagAnnotationFvRsApMonPolFvApResourceModel
			fvRsApMonPolFvApPlan.TagAnnotation.ElementsAs(ctx, &tagAnnotationFvRsApMonPolFvApPlan, false)
			if !fvRsApMonPolFvApState.TagAnnotation.IsNull() {
				fvRsApMonPolFvApState.TagAnnotation.ElementsAs(ctx, &tagAnnotationFvRsApMonPolFvApState, false)
			}
			if !fvRsApMonPolFvApPlan.TagAnnotation.IsNull() && !fvRsApMonPolFvApPlan.TagAnnotation.IsUnknown() {
				tagAnnotationIdentifiers := []TagAnnotationIdentifier{}
				for _, tagAnnotationFvRsApMonPolFvAp := range tagAnnotationFvRsApMonPolFvApPlan {
					tagAnnotationFvRsApMonPolFvApChildMap := NewAciObject()
					if !tagAnnotationFvRsApMonPolFvAp.Key.IsNull() && !tagAnnotationFvRsApMonPolFvAp.Key.IsUnknown() {
						tagAnnotationFvRsApMonPolFvApChildMap.Attributes["key"] = tagAnnotationFvRsApMonPolFvAp.Key.ValueString()
					}
					if !tagAnnotationFvRsApMonPolFvAp.Value.IsNull() && !tagAnnotationFvRsApMonPolFvAp.Value.IsUnknown() {
						tagAnnotationFvRsApMonPolFvApChildMap.Attributes["value"] = tagAnnotationFvRsApMonPolFvAp.Value.ValueString()
					}
					FvRsApMonPolFvApChildren = append(FvRsApMonPolFvApChildren, map[string]interface{}{"tagAnnotation": tagAnnotationFvRsApMonPolFvApChildMap})
					tagAnnotationIdentifier := TagAnnotationIdentifier{}
					tagAnnotationIdentifier.Key = tagAnnotationFvRsApMonPolFvAp.Key
					tagAnnotationIdentifiers = append(tagAnnotationIdentifiers, tagAnnotationIdentifier)
				}
				for _, tagAnnotationFvRsApMonPolFvAp := range tagAnnotationFvRsApMonPolFvApState {
					delete := true
					for _, tagAnnotationIdentifier := range tagAnnotationIdentifiers {
						if tagAnnotationIdentifier.Key == tagAnnotationFvRsApMonPolFvAp.Key {
							delete = false
							break
						}
					}
					if delete {
						tagAnnotationFvRsApMonPolFvApChildMapForDelete := NewAciObject()
						tagAnnotationFvRsApMonPolFvApChildMapForDelete.Attributes["status"] = "deleted"
						tagAnnotationFvRsApMonPolFvApChildMapForDelete.Attributes["key"] = tagAnnotationFvRsApMonPolFvAp.Key.ValueString()
						FvRsApMonPolFvApChildren = append(FvRsApMonPolFvApChildren, map[string]interface{}{"tagAnnotation": tagAnnotationFvRsApMonPolFvApChildMapForDelete})
					}
				}
			}

			var tagTagFvRsApMonPolFvApPlan, tagTagFvRsApMonPolFvApState []TagTagFvRsApMonPolFvApResourceModel
			fvRsApMonPolFvApPlan.TagTag.ElementsAs(ctx, &tagTagFvRsApMonPolFvApPlan, false)
			if !fvRsApMonPolFvApState.TagTag.IsNull() {
				fvRsApMonPolFvApState.TagTag.ElementsAs(ctx, &tagTagFvRsApMonPolFvApState, false)
			}
			if !fvRsApMonPolFvApPlan.TagTag.IsNull() && !fvRsApMonPolFvApPlan.TagTag.IsUnknown() {
				tagTagIdentifiers := []TagTagIdentifier{}
				for _, tagTagFvRsApMonPolFvAp := range tagTagFvRsApMonPolFvApPlan {
					tagTagFvRsApMonPolFvApChildMap := NewAciObject()
					if !tagTagFvRsApMonPolFvAp.Key.IsNull() && !tagTagFvRsApMonPolFvAp.Key.IsUnknown() {
						tagTagFvRsApMonPolFvApChildMap.Attributes["key"] = tagTagFvRsApMonPolFvAp.Key.ValueString()
					}
					if !tagTagFvRsApMonPolFvAp.Value.IsNull() && !tagTagFvRsApMonPolFvAp.Value.IsUnknown() {
						tagTagFvRsApMonPolFvApChildMap.Attributes["value"] = tagTagFvRsApMonPolFvAp.Value.ValueString()
					}
					FvRsApMonPolFvApChildren = append(FvRsApMonPolFvApChildren, map[string]interface{}{"tagTag": tagTagFvRsApMonPolFvApChildMap})
					tagTagIdentifier := TagTagIdentifier{}
					tagTagIdentifier.Key = tagTagFvRsApMonPolFvAp.Key
					tagTagIdentifiers = append(tagTagIdentifiers, tagTagIdentifier)
				}
				for _, tagTagFvRsApMonPolFvAp := range tagTagFvRsApMonPolFvApState {
					delete := true
					for _, tagTagIdentifier := range tagTagIdentifiers {
						if tagTagIdentifier.Key == tagTagFvRsApMonPolFvAp.Key {
							delete = false
							break
						}
					}
					if delete {
						tagTagFvRsApMonPolFvApChildMapForDelete := NewAciObject()
						tagTagFvRsApMonPolFvApChildMapForDelete.Attributes["status"] = "deleted"
						tagTagFvRsApMonPolFvApChildMapForDelete.Attributes["key"] = tagTagFvRsApMonPolFvAp.Key.ValueString()
						FvRsApMonPolFvApChildren = append(FvRsApMonPolFvApChildren, map[string]interface{}{"tagTag": tagTagFvRsApMonPolFvApChildMapForDelete})
					}
				}
			}
			childMap.Children = FvRsApMonPolFvApChildren
		} else {
			childMap.Attributes["status"] = "deleted"
		}
		childPayloads = append(childPayloads, map[string]interface{}{"fvRsApMonPol": childMap})
	} else {
		FvRsApMonPolObject, _ := types.ObjectValueFrom(ctx, FvRsApMonPolFvApType, getEmptyFvRsApMonPolFvApResourceModel())
		data.FvRsApMonPol = FvRsApMonPolObject
	}

	return childPayloads
}

func getFvApTagAnnotationChildPayloads(ctx context.Context, diags *diag.Diagnostics, data *FvApResourceModel, tagAnnotationFvApPlan, tagAnnotationFvApState []TagAnnotationFvApResourceModel) []map[string]interface{} {
	childPayloads := []map[string]interface{}{}
	if !data.TagAnnotation.IsNull() && !data.TagAnnotation.IsUnknown() {
		tagAnnotationIdentifiers := []TagAnnotationIdentifier{}
		for _, tagAnnotationFvAp := range tagAnnotationFvApPlan {
			childMap := NewAciObject()
			if !tagAnnotationFvAp.Key.IsNull() && !tagAnnotationFvAp.Key.IsUnknown() {
				childMap.Attributes["key"] = tagAnnotationFvAp.Key.ValueString()
			}
			if !tagAnnotationFvAp.Value.IsNull() && !tagAnnotationFvAp.Value.IsUnknown() {
				childMap.Attributes["value"] = tagAnnotationFvAp.Value.ValueString()
			}
			childPayloads = append(childPayloads, map[string]interface{}{"tagAnnotation": childMap})
			tagAnnotationIdentifier := TagAnnotationIdentifier{}
			tagAnnotationIdentifier.Key = tagAnnotationFvAp.Key
			tagAnnotationIdentifiers = append(tagAnnotationIdentifiers, tagAnnotationIdentifier)
		}
		for _, tagAnnotation := range tagAnnotationFvApState {
			delete := true
			for _, tagAnnotationIdentifier := range tagAnnotationIdentifiers {
				if tagAnnotationIdentifier.Key == tagAnnotation.Key {
					delete = false
					break
				}
			}
			if delete {
				tagAnnotationChildMapForDelete := NewAciObject()
				tagAnnotationChildMapForDelete.Attributes["status"] = "deleted"
				tagAnnotationChildMapForDelete.Attributes["key"] = tagAnnotation.Key.ValueString()
				childPayloads = append(childPayloads, map[string]interface{}{"tagAnnotation": tagAnnotationChildMapForDelete})
			}
		}
	} else {
		data.TagAnnotation = types.SetNull(data.TagAnnotation.ElementType(ctx))
	}

	return childPayloads
}

func getFvApTagTagChildPayloads(ctx context.Context, diags *diag.Diagnostics, data *FvApResourceModel, tagTagFvApPlan, tagTagFvApState []TagTagFvApResourceModel) []map[string]interface{} {
	childPayloads := []map[string]interface{}{}
	if !data.TagTag.IsNull() && !data.TagTag.IsUnknown() {
		tagTagIdentifiers := []TagTagIdentifier{}
		for _, tagTagFvAp := range tagTagFvApPlan {
			childMap := NewAciObject()
			if !tagTagFvAp.Key.IsNull() && !tagTagFvAp.Key.IsUnknown() {
				childMap.Attributes["key"] = tagTagFvAp.Key.ValueString()
			}
			if !tagTagFvAp.Value.IsNull() && !tagTagFvAp.Value.IsUnknown() {
				childMap.Attributes["value"] = tagTagFvAp.Value.ValueString()
			}
			childPayloads = append(childPayloads, map[string]interface{}{"tagTag": childMap})
			tagTagIdentifier := TagTagIdentifier{}
			tagTagIdentifier.Key = tagTagFvAp.Key
			tagTagIdentifiers = append(tagTagIdentifiers, tagTagIdentifier)
		}
		for _, tagTag := range tagTagFvApState {
			delete := true
			for _, tagTagIdentifier := range tagTagIdentifiers {
				if tagTagIdentifier.Key == tagTag.Key {
					delete = false
					break
				}
			}
			if delete {
				tagTagChildMapForDelete := NewAciObject()
				tagTagChildMapForDelete.Attributes["status"] = "deleted"
				tagTagChildMapForDelete.Attributes["key"] = tagTag.Key.ValueString()
				childPayloads = append(childPayloads, map[string]interface{}{"tagTag": tagTagChildMapForDelete})
			}
		}
	} else {
		data.TagTag = types.SetNull(data.TagTag.ElementType(ctx))
	}

	return childPayloads
}

func getFvApCreateJsonPayload(ctx context.Context, diags *diag.Diagnostics, createType bool, data *FvApResourceModel, fvRsApMonPolPlan, fvRsApMonPolState FvRsApMonPolFvApResourceModel, tagAnnotationPlan, tagAnnotationState []TagAnnotationFvApResourceModel, tagTagPlan, tagTagState []TagTagFvApResourceModel) *container.Container {
	payloadMap := map[string]interface{}{}
	payloadMap["attributes"] = map[string]string{}

	if createType && !globalAllowExistingOnCreate {
		payloadMap["attributes"].(map[string]string)["status"] = "created"
	}
	childPayloads := []map[string]interface{}{}

	FvRsApMonPolchildPayloads := getFvApFvRsApMonPolChildPayloads(ctx, diags, data, fvRsApMonPolPlan, fvRsApMonPolState)
	if FvRsApMonPolchildPayloads == nil {
		return nil
	}
	childPayloads = append(childPayloads, FvRsApMonPolchildPayloads...)

	TagAnnotationchildPayloads := getFvApTagAnnotationChildPayloads(ctx, diags, data, tagAnnotationPlan, tagAnnotationState)
	if TagAnnotationchildPayloads == nil {
		return nil
	}
	childPayloads = append(childPayloads, TagAnnotationchildPayloads...)

	TagTagchildPayloads := getFvApTagTagChildPayloads(ctx, diags, data, tagTagPlan, tagTagState)
	if TagTagchildPayloads == nil {
		return nil
	}
	childPayloads = append(childPayloads, TagTagchildPayloads...)

	payloadMap["children"] = childPayloads
	if !data.Annotation.IsNull() && !data.Annotation.IsUnknown() {
		payloadMap["attributes"].(map[string]string)["annotation"] = data.Annotation.ValueString()
	}
	if !data.Descr.IsNull() && !data.Descr.IsUnknown() {
		payloadMap["attributes"].(map[string]string)["descr"] = data.Descr.ValueString()
	}
	if !data.Name.IsNull() && !data.Name.IsUnknown() {
		payloadMap["attributes"].(map[string]string)["name"] = data.Name.ValueString()
	}
	if !data.NameAlias.IsNull() && !data.NameAlias.IsUnknown() {
		payloadMap["attributes"].(map[string]string)["nameAlias"] = data.NameAlias.ValueString()
	}
	if !data.OwnerKey.IsNull() && !data.OwnerKey.IsUnknown() {
		payloadMap["attributes"].(map[string]string)["ownerKey"] = data.OwnerKey.ValueString()
	}
	if !data.OwnerTag.IsNull() && !data.OwnerTag.IsUnknown() {
		payloadMap["attributes"].(map[string]string)["ownerTag"] = data.OwnerTag.ValueString()
	}
	if !data.Prio.IsNull() && !data.Prio.IsUnknown() {
		payloadMap["attributes"].(map[string]string)["prio"] = data.Prio.ValueString()
	}
	payload, err := json.Marshal(map[string]interface{}{"fvAp": payloadMap})
	if err != nil {
		diags.AddError(
			"Marshalling of json payload failed",
			fmt.Sprintf("Err: %s. Please report this issue to the provider developers.", err),
		)
		return nil
	}

	jsonPayload, err := container.ParseJSON(payload)

	if err != nil {
		diags.AddError(
			"Construction of json payload failed",
			fmt.Sprintf("Err: %s. Please report this issue to the provider developers.", err),
		)
		return nil
	}
	return jsonPayload
}
