// 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
package provider

// RESOURCE NORMAL
import (
	"context"
	"strconv"

	merakigosdk "github.com/meraki/dashboard-api-go/v5/sdk"

	"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/listplanmodifier"
	"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-framework/types/basetypes"
)

var (
	_ resource.Resource              = &NetworksApplianceSecurityMalwareResource{}
	_ resource.ResourceWithConfigure = &NetworksApplianceSecurityMalwareResource{}
)

func NewNetworksApplianceSecurityMalwareResource() resource.Resource {
	return &NetworksApplianceSecurityMalwareResource{}
}

type NetworksApplianceSecurityMalwareResource struct {
	client *merakigosdk.Client
}

func (r *NetworksApplianceSecurityMalwareResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
	if req.ProviderData == nil {
		return
	}
	client := req.ProviderData.(MerakiProviderData).Client
	r.client = client
}

// Metadata returns the data source type name.
func (r *NetworksApplianceSecurityMalwareResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
	resp.TypeName = req.ProviderTypeName + "_networks_appliance_security_malware"
}

func (r *NetworksApplianceSecurityMalwareResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
	resp.Schema = schema.Schema{
		Attributes: map[string]schema.Attribute{
			"allowed_files": schema.ListNestedAttribute{
				MarkdownDescription: `Sha256 digests of files permitted by the malware detection engine`,
				Optional:            true,
				PlanModifiers: []planmodifier.List{
					listplanmodifier.UseStateForUnknown(),
				},
				NestedObject: schema.NestedAttributeObject{
					Attributes: map[string]schema.Attribute{

						"comment": schema.StringAttribute{
							MarkdownDescription: `Comment about the allowed file`,
							Optional:            true,
							PlanModifiers: []planmodifier.String{
								stringplanmodifier.UseStateForUnknown(),
							},
						},
						"sha256": schema.StringAttribute{
							MarkdownDescription: `The sha256 digest of allowed file`,
							Optional:            true,
							PlanModifiers: []planmodifier.String{
								stringplanmodifier.UseStateForUnknown(),
							},
						},
					},
				},
			},
			"allowed_urls": schema.ListNestedAttribute{
				MarkdownDescription: `URLs permitted by the malware detection engine`,
				Optional:            true,
				PlanModifiers: []planmodifier.List{
					listplanmodifier.UseStateForUnknown(),
				},
				NestedObject: schema.NestedAttributeObject{
					Attributes: map[string]schema.Attribute{

						"comment": schema.StringAttribute{
							MarkdownDescription: `Comment about the allowed URL`,
							Optional:            true,
							PlanModifiers: []planmodifier.String{
								stringplanmodifier.UseStateForUnknown(),
							},
						},
						"url": schema.StringAttribute{
							MarkdownDescription: `The allowed URL`,
							Optional:            true,
							PlanModifiers: []planmodifier.String{
								stringplanmodifier.UseStateForUnknown(),
							},
						},
					},
				},
			},
			"mode": schema.StringAttribute{
				MarkdownDescription: `Current status of malware prevention
                                  Allowed values: [disabled,enabled]`,
				Optional: true,
				PlanModifiers: []planmodifier.String{
					stringplanmodifier.UseStateForUnknown(),
				},
				Validators: []validator.String{
					stringvalidator.OneOf(
						"disabled",
						"enabled",
					),
				},
			},
			"network_id": schema.StringAttribute{
				MarkdownDescription: `networkId path parameter. Network ID`,
				Required:            true,
			},
		},
	}
}

func (r *NetworksApplianceSecurityMalwareResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
	// Retrieve values from plan
	var data NetworksApplianceSecurityMalwareRs

	var item types.Object
	resp.Diagnostics.Append(req.Plan.Get(ctx, &item)...)
	if resp.Diagnostics.HasError() {
		return
	}

	resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{
		UnhandledNullAsEmpty:    true,
		UnhandledUnknownAsEmpty: true,
	})...)

	if resp.Diagnostics.HasError() {
		return
	}
	// Has Paths
	vvNetworkID := data.NetworkID.ValueString()
	//Has Item and not has items

	// UPDATE NO CREATE
	dataRequest := data.toSdkApiRequestUpdate(ctx)
	response, restyResp2, err := r.client.Appliance.UpdateNetworkApplianceSecurityMalware(vvNetworkID, dataRequest)
	//Update
	if err != nil || restyResp2 == nil || response == nil {
		if restyResp2 != nil {
			resp.Diagnostics.AddError(
				"Failure when executing UpdateNetworkApplianceSecurityMalware",
				"Status: "+strconv.Itoa(restyResp2.StatusCode())+"\n"+restyResp2.String(),
			)
			return
		}
		resp.Diagnostics.AddError(
			"Failure when executing UpdateNetworkApplianceSecurityMalware",
			err.Error(),
		)
		return
	}

	// Assign data
	resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)

}

func (r *NetworksApplianceSecurityMalwareResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	var data NetworksApplianceSecurityMalwareRs

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

	//Has Paths
	// Has Item2

	vvNetworkID := data.NetworkID.ValueString()
	responseGet, restyRespGet, err := r.client.Appliance.GetNetworkApplianceSecurityMalware(vvNetworkID)
	if err != nil || restyRespGet == nil {
		if restyRespGet != nil {
			if restyRespGet.StatusCode() == 404 {
				resp.Diagnostics.AddWarning(
					"Resource not found",
					"Deleting resource",
				)
				resp.State.RemoveResource(ctx)
				return
			}
			resp.Diagnostics.AddError(
				"Failure when executing GetNetworkApplianceSecurityMalware",
				restyRespGet.String(),
			)
			return
		}
		resp.Diagnostics.AddError(
			"Failure when executing GetNetworkApplianceSecurityMalware",
			err.Error(),
		)
		return
	}
	//entro aqui 2
	data = ResponseApplianceGetNetworkApplianceSecurityMalwareItemToBodyRs(data, responseGet, true)
	resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *NetworksApplianceSecurityMalwareResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
	resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("network_id"), req.ID)...)
}

func (r *NetworksApplianceSecurityMalwareResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
	var plan NetworksApplianceSecurityMalwareRs
	merge(ctx, req, resp, &plan)

	if resp.Diagnostics.HasError() {
		return
	}
	//Path Params
	vvNetworkID := plan.NetworkID.ValueString()
	dataRequest := plan.toSdkApiRequestUpdate(ctx)
	response, restyResp2, err := r.client.Appliance.UpdateNetworkApplianceSecurityMalware(vvNetworkID, dataRequest)
	if err != nil || restyResp2 == nil || response == nil {
		if restyResp2 != nil {
			resp.Diagnostics.AddError(
				"Failure when executing UpdateNetworkApplianceSecurityMalware",
				"Status: "+strconv.Itoa(restyResp2.StatusCode())+"\n"+restyResp2.String(),
			)
			return
		}
		resp.Diagnostics.AddError(
			"Failure when executing UpdateNetworkApplianceSecurityMalware",
			err.Error(),
		)
		return
	}
	resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}

func (r *NetworksApplianceSecurityMalwareResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	//missing delete
	resp.Diagnostics.AddWarning("Error deleting NetworksApplianceSecurityMalware", "This resource has no delete method in the meraki lab, the resource was deleted only in terraform.")
	resp.State.RemoveResource(ctx)
}

// TF Structs Schema
type NetworksApplianceSecurityMalwareRs struct {
	NetworkID    types.String                                                         `tfsdk:"network_id"`
	AllowedFiles *[]ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedFilesRs `tfsdk:"allowed_files"`
	AllowedURLs  *[]ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedUrlsRs  `tfsdk:"allowed_urls"`
	Mode         types.String                                                         `tfsdk:"mode"`
}

type ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedFilesRs struct {
	Comment types.String `tfsdk:"comment"`
	Sha256  types.String `tfsdk:"sha256"`
}

type ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedUrlsRs struct {
	Comment types.String `tfsdk:"comment"`
	URL     types.String `tfsdk:"url"`
}

// FromBody
func (r *NetworksApplianceSecurityMalwareRs) toSdkApiRequestUpdate(ctx context.Context) *merakigosdk.RequestApplianceUpdateNetworkApplianceSecurityMalware {
	emptyString := ""
	var requestApplianceUpdateNetworkApplianceSecurityMalwareAllowedFiles []merakigosdk.RequestApplianceUpdateNetworkApplianceSecurityMalwareAllowedFiles

	if r.AllowedFiles != nil {
		for _, rItem1 := range *r.AllowedFiles {
			comment := rItem1.Comment.ValueString()
			sha256 := rItem1.Sha256.ValueString()
			requestApplianceUpdateNetworkApplianceSecurityMalwareAllowedFiles = append(requestApplianceUpdateNetworkApplianceSecurityMalwareAllowedFiles, merakigosdk.RequestApplianceUpdateNetworkApplianceSecurityMalwareAllowedFiles{
				Comment: comment,
				Sha256:  sha256,
			})
			//[debug] Is Array: True
		}
	}
	var requestApplianceUpdateNetworkApplianceSecurityMalwareAllowedURLs []merakigosdk.RequestApplianceUpdateNetworkApplianceSecurityMalwareAllowedURLs

	if r.AllowedURLs != nil {
		for _, rItem1 := range *r.AllowedURLs {
			comment := rItem1.Comment.ValueString()
			url := rItem1.URL.ValueString()
			requestApplianceUpdateNetworkApplianceSecurityMalwareAllowedURLs = append(requestApplianceUpdateNetworkApplianceSecurityMalwareAllowedURLs, merakigosdk.RequestApplianceUpdateNetworkApplianceSecurityMalwareAllowedURLs{
				Comment: comment,
				URL:     url,
			})
			//[debug] Is Array: True
		}
	}
	mode := new(string)
	if !r.Mode.IsUnknown() && !r.Mode.IsNull() {
		*mode = r.Mode.ValueString()
	} else {
		mode = &emptyString
	}
	out := merakigosdk.RequestApplianceUpdateNetworkApplianceSecurityMalware{
		AllowedFiles: func() *[]merakigosdk.RequestApplianceUpdateNetworkApplianceSecurityMalwareAllowedFiles {
			if len(requestApplianceUpdateNetworkApplianceSecurityMalwareAllowedFiles) > 0 {
				return &requestApplianceUpdateNetworkApplianceSecurityMalwareAllowedFiles
			}
			return nil
		}(),
		AllowedURLs: func() *[]merakigosdk.RequestApplianceUpdateNetworkApplianceSecurityMalwareAllowedURLs {
			if len(requestApplianceUpdateNetworkApplianceSecurityMalwareAllowedURLs) > 0 {
				return &requestApplianceUpdateNetworkApplianceSecurityMalwareAllowedURLs
			}
			return nil
		}(),
		Mode: *mode,
	}
	return &out
}

// From gosdk to TF Structs Schema
func ResponseApplianceGetNetworkApplianceSecurityMalwareItemToBodyRs(state NetworksApplianceSecurityMalwareRs, response *merakigosdk.ResponseApplianceGetNetworkApplianceSecurityMalware, is_read bool) NetworksApplianceSecurityMalwareRs {
	itemState := NetworksApplianceSecurityMalwareRs{
		AllowedFiles: func() *[]ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedFilesRs {
			if response.AllowedFiles != nil {
				result := make([]ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedFilesRs, len(*response.AllowedFiles))
				for i, allowedFiles := range *response.AllowedFiles {
					result[i] = ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedFilesRs{
						Comment: func() types.String {
							if allowedFiles.Comment != "" {
								return types.StringValue(allowedFiles.Comment)
							}
							return types.String{}
						}(),
						Sha256: func() types.String {
							if allowedFiles.Sha256 != "" {
								return types.StringValue(allowedFiles.Sha256)
							}
							return types.String{}
						}(),
					}
				}
				return &result
			}
			return nil
		}(),
		AllowedURLs: func() *[]ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedUrlsRs {
			if response.AllowedURLs != nil {
				result := make([]ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedUrlsRs, len(*response.AllowedURLs))
				for i, allowedURLs := range *response.AllowedURLs {
					result[i] = ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedUrlsRs{
						Comment: func() types.String {
							if allowedURLs.Comment != "" {
								return types.StringValue(allowedURLs.Comment)
							}
							return types.String{}
						}(),
						URL: func() types.String {
							if allowedURLs.URL != "" {
								return types.StringValue(allowedURLs.URL)
							}
							return types.String{}
						}(),
					}
				}
				return &result
			}
			return nil
		}(),
		Mode: func() types.String {
			if response.Mode != "" {
				return types.StringValue(response.Mode)
			}
			return types.String{}
		}(),
	}
	if is_read {
		return mergeInterfacesOnlyPath(state, itemState).(NetworksApplianceSecurityMalwareRs)
	}
	return mergeInterfaces(state, itemState, true).(NetworksApplianceSecurityMalwareRs)
}
