// Copyright © 2023 Cisco Systems, Inc. and its affiliates.
// All rights reserved.
//
// Licensed under the Mozilla Public 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
//
//     https://mozilla.org/MPL/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.
//
// SPDX-License-Identifier: MPL-2.0

// Code generated by "gen/generator.go"; DO NOT EDIT.

package provider

// Section below is generated&owned by "gen/generator.go". //template:begin imports
import (
	"context"
	"fmt"
	"strings"

	"github.com/CiscoDevNet/terraform-provider-iosxe/internal/provider/helpers"
	"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
	"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
	"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/planmodifier"
	"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-log/tflog"
	"github.com/netascode/go-restconf"
)

// End of section. //template:end imports

// Section below is generated&owned by "gen/generator.go". //template:begin model

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

func NewPolicyMapEventResource() resource.Resource {
	return &PolicyMapEventResource{}
}

type PolicyMapEventResource struct {
	data *IosxeProviderData
}

func (r *PolicyMapEventResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
	resp.TypeName = req.ProviderTypeName + "_policy_map_event"
}

func (r *PolicyMapEventResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
	resp.Schema = schema.Schema{
		// This description is used by the documentation generator and the language server.
		MarkdownDescription: "This resource can manage the Policy Map Event configuration.",

		Attributes: map[string]schema.Attribute{
			"device": schema.StringAttribute{
				MarkdownDescription: "A device name from the provider configuration.",
				Optional:            true,
			},
			"id": schema.StringAttribute{
				MarkdownDescription: "The path of the object.",
				Computed:            true,
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
				},
			},
			"name": schema.StringAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Name of the policy map").String,
				Required:            true,
				Validators: []validator.String{
					stringvalidator.LengthBetween(1, 203),
				},
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.RequiresReplace(),
				},
			},
			"event_type": schema.StringAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("The event this control class-map triggers upon").AddStringEnumDescription("aaa-available", "absolute-timeout", "agent-found", "authentication-failure", "authentication-success", "authorization-failure", "authorization-success", "identity-update", "inactivity-timeout", "remote-authentication-failure", "remote-authentication-success", "remote-update", "session-disconnected", "session-started", "tag-added", "tag-removed", "template-activated", "template-activation-failed", "template-deactivated", "template-deactivation-failed", "timer-expiry", "violation").String,
				Required:            true,
				Validators: []validator.String{
					stringvalidator.OneOf("aaa-available", "absolute-timeout", "agent-found", "authentication-failure", "authentication-success", "authorization-failure", "authorization-success", "identity-update", "inactivity-timeout", "remote-authentication-failure", "remote-authentication-success", "remote-update", "session-disconnected", "session-started", "tag-added", "tag-removed", "template-activated", "template-activation-failed", "template-deactivated", "template-deactivation-failed", "timer-expiry", "violation"),
				},
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.RequiresReplace(),
				},
			},
			"match_type": schema.StringAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Matching criteria for first or all events.").AddStringEnumDescription("match-all", "match-first").String,
				Optional:            true,
				Validators: []validator.String{
					stringvalidator.OneOf("match-all", "match-first"),
				},
			},
			"class_numbers": schema.ListNestedAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("class number, 1 for 1st class, 2 for 2nd...").String,
				Optional:            true,
				NestedObject: schema.NestedAttributeObject{
					Attributes: map[string]schema.Attribute{
						"number": schema.Int64Attribute{
							MarkdownDescription: helpers.NewAttributeDescription("class number, 1 for 1st class, 2 for 2nd...").AddIntegerRangeDescription(1, 254).String,
							Required:            true,
							Validators: []validator.Int64{
								int64validator.Between(1, 254),
							},
						},
						"class": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("The class type this control policy-map triggers upon").String,
							Optional:            true,
						},
						"execution_type": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Policy execution strategy").AddStringEnumDescription("do-all", "do-until-failure", "do-until-success").String,
							Optional:            true,
							Validators: []validator.String{
								stringvalidator.OneOf("do-all", "do-until-failure", "do-until-success"),
							},
						},
						"action_numbers": schema.ListNestedAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("action number, 1 for 1st class, 2 for 2nd...").String,
							Optional:            true,
							NestedObject: schema.NestedAttributeObject{
								Attributes: map[string]schema.Attribute{
									"number": schema.Int64Attribute{
										MarkdownDescription: helpers.NewAttributeDescription("action number, 1 for 1st class, 2 for 2nd...").AddIntegerRangeDescription(1, 254).String,
										Required:            true,
										Validators: []validator.Int64{
											int64validator.Between(1, 254),
										},
									},
									"pause_reauthentication": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("pause reauthentication").String,
										Optional:            true,
									},
									"authorize": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("authorize session").String,
										Optional:            true,
									},
									"terminate_config": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("terminate auth method").AddStringEnumDescription("dot1x", "mab", "webauth").String,
										Optional:            true,
										Validators: []validator.String{
											stringvalidator.OneOf("dot1x", "mab", "webauth"),
										},
									},
									"activate_service_template_config_service_template": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("activate service template").String,
										Optional:            true,
										Validators: []validator.String{
											stringvalidator.LengthBetween(1, 48),
										},
									},
									"activate_service_template_config_aaa_list": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("Named Method List").String,
										Optional:            true,
									},
									"activate_service_template_config_precedence": schema.Int64Attribute{
										MarkdownDescription: helpers.NewAttributeDescription("Template precedence").AddIntegerRangeDescription(1, 254).String,
										Optional:            true,
										Validators: []validator.Int64{
											int64validator.Between(1, 254),
										},
									},
									"activate_service_template_config_replace_all": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("Replace all existing authorization data and services").String,
										Optional:            true,
									},
									"activate_interface_template": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("activate interface template").String,
										Optional:            true,
									},
									"activate_policy_type_control_subscriber": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("policy type control subscriber").String,
										Optional:            true,
									},
									"deactivate_interface_template": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("activate interface template").String,
										Optional:            true,
									},
									"deactivate_service_template": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("activate service template").String,
										Optional:            true,
									},
									"deactivate_policy_type_control_subscriber": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("policy type control subscriber").String,
										Optional:            true,
									},
									"authenticate_using_method": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("method/protocol to be used for authentication").AddStringEnumDescription("dot1x", "mab", "webauth").String,
										Optional:            true,
										Validators: []validator.String{
											stringvalidator.OneOf("dot1x", "mab", "webauth"),
										},
									},
									"authenticate_using_retries": schema.Int64Attribute{
										MarkdownDescription: helpers.NewAttributeDescription("Number of times to retry failed authentications").AddIntegerRangeDescription(1, 5).String,
										Optional:            true,
										Validators: []validator.Int64{
											int64validator.Between(1, 5),
										},
									},
									"authenticate_using_retry_time": schema.Int64Attribute{
										MarkdownDescription: helpers.NewAttributeDescription("Time interval between retries").AddIntegerRangeDescription(0, 65535).String,
										Optional:            true,
										Validators: []validator.Int64{
											int64validator.Between(0, 65535),
										},
									},
									"authenticate_using_priority": schema.Int64Attribute{
										MarkdownDescription: helpers.NewAttributeDescription("Method priority").AddIntegerRangeDescription(1, 254).String,
										Optional:            true,
										Validators: []validator.Int64{
											int64validator.Between(1, 254),
										},
									},
									"authenticate_using_aaa_authc_list": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("Specify authentication method list").String,
										Optional:            true,
									},
									"authenticate_using_aaa_authz_list": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("Specify authorization method list").String,
										Optional:            true,
									},
									"authenticate_using_both": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("Enabling Dot1x Authenticator & Supplicant").String,
										Optional:            true,
									},
									"authenticate_using_parameter_map": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("Specify parameter map name").String,
										Optional:            true,
									},
									"replace": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("clear existing session and create session for violating host").String,
										Optional:            true,
									},
									"restrict": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("drop violating packets and generate a syslog").String,
										Optional:            true,
									},
									"clear_session": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("clears an active session").String,
										Optional:            true,
									},
									"clear_authenticated_data_hosts_on_port": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("clears authenticated data hosts on the port").String,
										Optional:            true,
									},
									"protect": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("silently drop violating packets").String,
										Optional:            true,
									},
									"err_disable": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("temporarily disable port").String,
										Optional:            true,
									},
									"resume_reauthentication": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("resume reauthentication").String,
										Optional:            true,
									},
									"authentication_restart": schema.Int64Attribute{
										MarkdownDescription: helpers.NewAttributeDescription("restarts the auth sequence after the specified number of sec").AddIntegerRangeDescription(1, 65535).String,
										Optional:            true,
										Validators: []validator.Int64{
											int64validator.Between(1, 65535),
										},
									},
									"set_domain": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("set domain").AddStringEnumDescription("data", "switch", "voice").String,
										Optional:            true,
										Validators: []validator.String{
											stringvalidator.OneOf("data", "switch", "voice"),
										},
									},
									"unauthorize": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("unauthorize session").String,
										Optional:            true,
									},
									"notify": schema.BoolAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("notifies the session attributes").String,
										Optional:            true,
									},
									"set_timer_name": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("timer name").String,
										Optional:            true,
									},
									"set_timer_value": schema.Int64Attribute{
										MarkdownDescription: helpers.NewAttributeDescription("Enter a value between 1 and 65535").AddIntegerRangeDescription(0, 65535).String,
										Optional:            true,
										Validators: []validator.Int64{
											int64validator.Between(0, 65535),
										},
									},
									"map_attribute_to_service_table": schema.StringAttribute{
										MarkdownDescription: helpers.NewAttributeDescription("map identity-update attribute to a auto-conf templates").String,
										Optional:            true,
									},
								},
							},
						},
					},
				},
			},
		},
	}
}

func (r *PolicyMapEventResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) {
	if req.ProviderData == nil {
		return
	}

	r.data = req.ProviderData.(*IosxeProviderData)
}

// End of section. //template:end model

// Section below is generated&owned by "gen/generator.go". //template:begin create

func (r *PolicyMapEventResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
	var plan PolicyMapEvent

	// Read plan
	diags := req.Plan.Get(ctx, &plan)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		return
	}

	tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.getPath()))

	device, ok := r.data.Devices[plan.Device.ValueString()]
	if !ok {
		resp.Diagnostics.AddAttributeError(path.Root("device"), "Invalid device", fmt.Sprintf("Device '%s' does not exist in provider configuration.", plan.Device.ValueString()))
		return
	}

	if device.Managed {
		// Create object
		body := plan.toBody(ctx)

		emptyLeafsDelete := plan.getEmptyLeafsDelete(ctx)
		tflog.Debug(ctx, fmt.Sprintf("List of empty leafs to delete: %+v", emptyLeafsDelete))

		if YangPatch {
			edits := []restconf.YangPatchEdit{restconf.NewYangPatchEdit("merge", plan.getPath(), restconf.Body{Str: body})}
			for _, i := range emptyLeafsDelete {
				edits = append(edits, restconf.NewYangPatchEdit("remove", i, restconf.Body{}))
			}
			_, err := device.Client.YangPatchData("", "1", "", edits)
			if err != nil {
				resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object, got error: %s", err))
				return
			}
		} else {
			res, err := device.Client.PatchData(plan.getPathShort(), body)
			if len(res.Errors.Error) > 0 && res.Errors.Error[0].ErrorMessage == "patch to a nonexistent resource" {
				_, err = device.Client.PutData(plan.getPath(), body)
			}
			if err != nil {
				resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PATCH, %s), got error: %s", plan.getPathShort(), err))
				return
			}
			for _, i := range emptyLeafsDelete {
				res, err := device.Client.DeleteData(i)
				if err != nil && res.StatusCode != 404 {
					resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (%s), got error: %s", i, err))
					return
				}
			}
		}
	}

	plan.Id = types.StringValue(plan.getPath())

	tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.getPath()))

	diags = resp.State.Set(ctx, &plan)
	resp.Diagnostics.Append(diags...)

	helpers.SetFlagImporting(ctx, false, resp.Private, &resp.Diagnostics)
}

// End of section. //template:end create

// Section below is generated&owned by "gen/generator.go". //template:begin read

func (r *PolicyMapEventResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	var state PolicyMapEvent

	// Read state
	diags := req.State.Get(ctx, &state)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		return
	}

	tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.ValueString()))

	device, ok := r.data.Devices[state.Device.ValueString()]
	if !ok {
		resp.Diagnostics.AddAttributeError(path.Root("device"), "Invalid device", fmt.Sprintf("Device '%s' does not exist in provider configuration.", state.Device.ValueString()))
		return
	}

	if device.Managed {
		res, err := device.Client.GetData(state.Id.ValueString())
		if res.StatusCode == 404 {
			state = PolicyMapEvent{Device: state.Device, Id: state.Id}
		} else {
			if err != nil {
				resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (%s), got error: %s", state.Id.ValueString(), err))
				return
			}

			imp, diags := helpers.IsFlagImporting(ctx, req)
			if resp.Diagnostics.Append(diags...); resp.Diagnostics.HasError() {
				return
			}

			// After `terraform import` we switch to a full read.
			if imp {
				state.fromBody(ctx, res.Res)
			} else {
				state.updateFromBody(ctx, res.Res)
			}
		}
	}

	tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString()))

	diags = resp.State.Set(ctx, &state)
	resp.Diagnostics.Append(diags...)

	helpers.SetFlagImporting(ctx, false, resp.Private, &resp.Diagnostics)
}

// End of section. //template:end read

// Section below is generated&owned by "gen/generator.go". //template:begin update

func (r *PolicyMapEventResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
	var plan, state PolicyMapEvent

	// Read plan
	diags := req.Plan.Get(ctx, &plan)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		return
	}

	// Read state
	diags = req.State.Get(ctx, &state)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		return
	}

	tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString()))

	device, ok := r.data.Devices[plan.Device.ValueString()]
	if !ok {
		resp.Diagnostics.AddAttributeError(path.Root("device"), "Invalid device", fmt.Sprintf("Device '%s' does not exist in provider configuration.", plan.Device.ValueString()))
		return
	}

	if device.Managed {
		body := plan.toBody(ctx)

		deletedItems := plan.getDeletedItems(ctx, state)
		tflog.Debug(ctx, fmt.Sprintf("Removed items to delete: %+v", deletedItems))

		emptyLeafsDelete := plan.getEmptyLeafsDelete(ctx)
		tflog.Debug(ctx, fmt.Sprintf("List of empty leafs to delete: %+v", emptyLeafsDelete))

		if YangPatch {
			var edits []restconf.YangPatchEdit
			for _, i := range deletedItems {
				edits = append(edits, restconf.NewYangPatchEdit("remove", i, restconf.Body{}))
			}
			edits = append(edits, restconf.NewYangPatchEdit("merge", plan.getPath(), restconf.Body{Str: body}))
			for _, i := range emptyLeafsDelete {
				edits = append(edits, restconf.NewYangPatchEdit("remove", i, restconf.Body{}))
			}
			_, err := device.Client.YangPatchData("", "1", "", edits)
			if err != nil {
				resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to update object, got error: %s", err))
				return
			}
		} else {
			for _, i := range deletedItems {
				res, err := device.Client.DeleteData(i)
				if err != nil && res.StatusCode != 404 {
					resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (%s), got error: %s", i, err))
					return
				}
			}
			res, err := device.Client.PatchData(plan.getPathShort(), body)
			if len(res.Errors.Error) > 0 && res.Errors.Error[0].ErrorMessage == "patch to a nonexistent resource" {
				_, err = device.Client.PutData(plan.getPath(), body)
			}
			if err != nil {
				resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PATCH, %s), got error: %s", plan.getPathShort(), err))
				return
			}
			for _, i := range emptyLeafsDelete {
				res, err := device.Client.DeleteData(i)
				if err != nil && res.StatusCode != 404 {
					resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (%s), got error: %s", i, err))
					return
				}
			}
		}
	}

	tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString()))

	diags = resp.State.Set(ctx, &plan)
	resp.Diagnostics.Append(diags...)
}

// End of section. //template:end update

// Section below is generated&owned by "gen/generator.go". //template:begin delete

func (r *PolicyMapEventResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	var state PolicyMapEvent

	// Read state
	diags := req.State.Get(ctx, &state)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		return
	}

	tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString()))

	device, ok := r.data.Devices[state.Device.ValueString()]
	if !ok {
		resp.Diagnostics.AddAttributeError(path.Root("device"), "Invalid device", fmt.Sprintf("Device '%s' does not exist in provider configuration.", state.Device.ValueString()))
		return
	}

	if device.Managed {
		deleteMode := "all"

		if deleteMode == "all" {
			res, err := device.Client.DeleteData(state.Id.ValueString())
			if err != nil && res.StatusCode != 404 && res.StatusCode != 400 {
				resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (%s), got error: %s", state.Id.ValueString(), err))
				return
			}
		} else {
			deletePaths := state.getDeletePaths(ctx)
			tflog.Debug(ctx, fmt.Sprintf("Paths to delete: %+v", deletePaths))

			if YangPatch {
				edits := []restconf.YangPatchEdit{}
				for _, i := range deletePaths {
					edits = append(edits, restconf.NewYangPatchEdit("remove", i, restconf.Body{}))
				}
				_, err := device.Client.YangPatchData("", "1", "", edits)
				if err != nil {
					resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object, got error: %s", err))
					return
				}
			} else {
				for _, i := range deletePaths {
					res, err := device.Client.DeleteData(i)
					if err != nil && res.StatusCode != 404 {
						resp.Diagnostics.AddWarning("Client Warning", fmt.Sprintf("Failed to delete object (%s), got error: %s", i, err))
					}
				}
			}
		}
	}

	tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString()))

	resp.State.RemoveResource(ctx)
}

// End of section. //template:end delete

// Section below is generated&owned by "gen/generator.go". //template:begin import

func (r *PolicyMapEventResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
	idParts := strings.Split(req.ID, ",")
	idParts = helpers.RemoveEmptyStrings(idParts)

	if len(idParts) != 2 && len(idParts) != 3 {
		expectedIdentifier := "Expected import identifier with format: '<name>,<event_type>'"
		expectedIdentifier += " or '<name>,<event_type>,<device>'"
		resp.Diagnostics.AddError(
			"Unexpected Import Identifier",
			fmt.Sprintf("%s. Got: %q", expectedIdentifier, req.ID),
		)
		return
	}
	resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), idParts[0])...)
	resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("event_type"), idParts[1])...)
	if len(idParts) == 3 {
		resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("device"), idParts[len(idParts)-1])...)
	}

	// construct path for 'id' attribute
	var state PolicyMapEvent
	diags := resp.State.Get(ctx, &state)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		return
	}
	resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), state.getPath())...)

	helpers.SetFlagImporting(ctx, true, resp.Private, &resp.Diagnostics)
}

// End of section. //template:end import
