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

package provider

import (
	"context"
	"fmt"
	"sync"

	"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-sdwan"
	"github.com/netascode/terraform-provider-sdwan/internal/provider/helpers"
)

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

func NewCiscoSecurityFeatureTemplateResource() resource.Resource {
	return &CiscoSecurityFeatureTemplateResource{}
}

type CiscoSecurityFeatureTemplateResource struct {
	client      *sdwan.Client
	updateMutex *sync.Mutex
}

func (r *CiscoSecurityFeatureTemplateResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
	resp.TypeName = req.ProviderTypeName + "_cisco_security_feature_template"
}

func (r *CiscoSecurityFeatureTemplateResource) 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: helpers.NewAttributeDescription("This resource can manage a Cisco Security feature template.").AddMinimumVersionDescription("15.0.0").String,

		Attributes: map[string]schema.Attribute{
			"id": schema.StringAttribute{
				MarkdownDescription: "The id of the feature template",
				Computed:            true,
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
				},
			},
			"version": schema.Int64Attribute{
				MarkdownDescription: "The version of the feature template",
				Computed:            true,
			},
			"template_type": schema.StringAttribute{
				MarkdownDescription: "The template type",
				Computed:            true,
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
				},
			},
			"name": schema.StringAttribute{
				MarkdownDescription: "The name of the feature template",
				Required:            true,
			},
			"description": schema.StringAttribute{
				MarkdownDescription: "The description of the feature template",
				Required:            true,
			},
			"device_types": schema.ListAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("List of supported device types").AddStringEnumDescription("vedge-C8000V", "vedge-C8300-1N1S-4T2X", "vedge-C8300-1N1S-6T", "vedge-C8300-2N2S-6T", "vedge-C8300-2N2S-4T2X", "vedge-C8500-12X4QC", "vedge-C8500-12X", "vedge-C8500-20X6C", "vedge-C8500L-8S4X", "vedge-C8200-1N-4T", "vedge-C8200L-1N-4T").String,
				ElementType:         types.StringType,
				Required:            true,
			},
			"rekey_interval": schema.Int64Attribute{
				MarkdownDescription: helpers.NewAttributeDescription("Set how often to change the AES key for DTLS connections").AddIntegerRangeDescription(10, 1209600).AddDefaultValueDescription("86400").String,
				Optional:            true,
				Validators: []validator.Int64{
					int64validator.Between(10, 1209600),
				},
			},
			"rekey_interval_variable": schema.StringAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
				Optional:            true,
			},
			"replay_window": schema.StringAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Set the sliding replay window size").AddStringEnumDescription("64", "128", "256", "512", "1024", "2048", "4096", "8192").AddDefaultValueDescription("512").String,
				Optional:            true,
				Validators: []validator.String{
					stringvalidator.OneOf("64", "128", "256", "512", "1024", "2048", "4096", "8192"),
				},
			},
			"replay_window_variable": schema.StringAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
				Optional:            true,
			},
			"extended_ar_window": schema.Int64Attribute{
				MarkdownDescription: helpers.NewAttributeDescription("Extended Anti-Replay Window").AddIntegerRangeDescription(10, 2048).AddDefaultValueDescription("256").String,
				Optional:            true,
				Validators: []validator.Int64{
					int64validator.Between(10, 2048),
				},
			},
			"extended_ar_window_variable": schema.StringAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
				Optional:            true,
			},
			"authentication_type": schema.ListAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Set the authentication type for DTLS connections").String,
				ElementType:         types.StringType,
				Optional:            true,
			},
			"authentication_type_variable": schema.StringAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
				Optional:            true,
			},
			"integrity_type": schema.ListAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Set the authentication type for DTLS connections").String,
				ElementType:         types.StringType,
				Optional:            true,
			},
			"integrity_type_variable": schema.StringAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
				Optional:            true,
			},
			"pairwise_keying": schema.BoolAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Enable or disable IPsec pairwise-keying").AddDefaultValueDescription("false").String,
				Optional:            true,
			},
			"pairwise_keying_variable": schema.StringAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
				Optional:            true,
			},
			"keychains": schema.ListNestedAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Configure a Keychain").String,
				Optional:            true,
				NestedObject: schema.NestedAttributeObject{
					Attributes: map[string]schema.Attribute{
						"name": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Specify the name of the Keychain").String,
							Optional:            true,
							Validators: []validator.String{
								stringvalidator.LengthBetween(0, 236),
							},
						},
						"key_id": schema.Int64Attribute{
							MarkdownDescription: helpers.NewAttributeDescription("Specify the Key ID").AddIntegerRangeDescription(0, 2147483647).String,
							Optional:            true,
							Validators: []validator.Int64{
								int64validator.Between(0, 2147483647),
							},
						},
						"optional": schema.BoolAttribute{
							MarkdownDescription: "Indicates if list item is considered optional.",
							Optional:            true,
						},
					},
				},
			},
			"keys": schema.ListNestedAttribute{
				MarkdownDescription: helpers.NewAttributeDescription("Configure a Key").String,
				Optional:            true,
				NestedObject: schema.NestedAttributeObject{
					Attributes: map[string]schema.Attribute{
						"id": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Select the Key ID").String,
							Optional:            true,
						},
						"chain_name": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Select the chain name").String,
							Optional:            true,
						},
						"send_id": schema.Int64Attribute{
							MarkdownDescription: helpers.NewAttributeDescription("Specify the Send ID").AddIntegerRangeDescription(0, 255).AddDefaultValueDescription("0").String,
							Optional:            true,
							Validators: []validator.Int64{
								int64validator.Between(0, 255),
							},
						},
						"send_id_variable": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
							Optional:            true,
						},
						"receive_id": schema.Int64Attribute{
							MarkdownDescription: helpers.NewAttributeDescription("Specify the Receiver ID").AddIntegerRangeDescription(0, 255).AddDefaultValueDescription("0").String,
							Optional:            true,
							Validators: []validator.Int64{
								int64validator.Between(0, 255),
							},
						},
						"receive_id_variable": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
							Optional:            true,
						},
						"crypto_algorithm": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Crypto Algorithm").AddStringEnumDescription("aes-128-cmac", "hmac-sha-1", "hmac-sha-256").String,
							Optional:            true,
							Validators: []validator.String{
								stringvalidator.OneOf("aes-128-cmac", "hmac-sha-1", "hmac-sha-256"),
							},
						},
						"key_string": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Specify the Key String").String,
							Optional:            true,
						},
						"key_string_variable": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
							Optional:            true,
						},
						"send_lifetime": schema.BoolAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Send lifetime Local").AddDefaultValueDescription("false").String,
							Optional:            true,
						},
						"send_lifetime_variable": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
							Optional:            true,
						},
						"send_lifetime_start_time": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Key lifetime start time").String,
							Optional:            true,
						},
						"send_lifetime_end_time_format": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Key lifetime end time").AddStringEnumDescription("infinite", "duration", "end-epoch").AddDefaultValueDescription("infinite").String,
							Optional:            true,
							Validators: []validator.String{
								stringvalidator.OneOf("infinite", "duration", "end-epoch"),
							},
						},
						"send_lifetime_duration": schema.Int64Attribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Send lifetime Duration").AddIntegerRangeDescription(1, 2147483646).String,
							Optional:            true,
							Validators: []validator.Int64{
								int64validator.Between(1, 2147483646),
							},
						},
						"send_lifetime_duration_variable": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
							Optional:            true,
						},
						"send_lifetime_end_time": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Key lifetime end time").String,
							Optional:            true,
						},
						"send_lifetime_infinite": schema.BoolAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Key lifetime end time").String,
							Optional:            true,
						},
						"send_lifetime_infinite_variable": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
							Optional:            true,
						},
						"accept_lifetime": schema.BoolAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Accept Lifetime Local").AddDefaultValueDescription("false").String,
							Optional:            true,
						},
						"accept_lifetime_variable": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
							Optional:            true,
						},
						"accept_lifetime_start_time": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Key lifetime start time").String,
							Optional:            true,
						},
						"accept_lifetime_end_time_format": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Key lifetime end time").AddStringEnumDescription("infinite", "duration", "end-epoch").AddDefaultValueDescription("infinite").String,
							Optional:            true,
							Validators: []validator.String{
								stringvalidator.OneOf("infinite", "duration", "end-epoch"),
							},
						},
						"accept_lifetime_duration": schema.Int64Attribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Accept lifetime Duration").AddIntegerRangeDescription(1, 2147483646).String,
							Optional:            true,
							Validators: []validator.Int64{
								int64validator.Between(1, 2147483646),
							},
						},
						"accept_lifetime_duration_variable": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
							Optional:            true,
						},
						"accept_lifetime_end_time": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Key lifetime end time").String,
							Optional:            true,
						},
						"accept_lifetime_infinite": schema.BoolAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Key lifetime end time").String,
							Optional:            true,
						},
						"accept_lifetime_infinite_variable": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
							Optional:            true,
						},
						"include_tcp_options": schema.BoolAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Include TCP Options").AddDefaultValueDescription("false").String,
							Optional:            true,
						},
						"include_tcp_options_variable": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
							Optional:            true,
						},
						"accept_ao_mismatch": schema.BoolAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Configure Accept AO Mismatch").AddDefaultValueDescription("false").String,
							Optional:            true,
						},
						"accept_ao_mismatch_variable": schema.StringAttribute{
							MarkdownDescription: helpers.NewAttributeDescription("Variable name").String,
							Optional:            true,
						},
						"optional": schema.BoolAttribute{
							MarkdownDescription: "Indicates if list item is considered optional.",
							Optional:            true,
						},
					},
				},
			},
		},
	}
}

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

	r.client = req.ProviderData.(*SdwanProviderData).Client
	r.updateMutex = req.ProviderData.(*SdwanProviderData).UpdateMutex
}

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

	// 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.Name.ValueString()))

	// Create object
	body := plan.toBody(ctx)

	res, err := r.client.Post("/template/feature", body)
	if err != nil {
		resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String()))
		return
	}

	plan.Id = types.StringValue(res.Get("templateId").String())
	plan.Version = types.Int64Value(0)
	plan.TemplateType = types.StringValue(plan.getModel())

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

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

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

	// 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.Name.String()))

	res, err := r.client.Get("/template/feature/object/" + state.Id.ValueString())
	if res.Get("error.message").String() == "Invalid Template Id" {
		resp.State.RemoveResource(ctx)
		return
	} else if err != nil {
		resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String()))
		return
	}

	state.fromBody(ctx, res)

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

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

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

	// 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.Name.ValueString()))

	body := plan.toBody(ctx)
	r.updateMutex.Lock()
	res, err := r.client.Put("/template/feature/"+plan.Id.ValueString(), body)
	r.updateMutex.Unlock()
	if err != nil {
		if res.Get("error.message").String() == "Template locked in edit mode." {
			resp.Diagnostics.AddWarning("Client Warning", fmt.Sprintf("Failed to modify template due to template being locked by another change. Template changes will not be applied. Re-run 'terraform apply' to try again."))
		} else {
			resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String()))
			return
		}
	}

	if plan.hasChanges(ctx, &state) {
		plan.Version = types.Int64Value(state.Version.ValueInt64() + 1)
	} else {
		plan.Version = state.Version
	}

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

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

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

	// 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.Name.ValueString()))

	res, err := r.client.Delete("/template/feature/" + state.Id.ValueString())
	if err != nil && res.Get("error.message").String() != "Invalid Template Id" {
		resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String()))
		return
	}

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

	resp.State.RemoveResource(ctx)
}

func (r *CiscoSecurityFeatureTemplateResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
	resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
