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

// DATA SOURCE NORMAL
import (
	"context"
	"log"

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

	"github.com/hashicorp/terraform-plugin-framework/datasource"
	"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
	"github.com/hashicorp/terraform-plugin-framework/types"
)

var (
	_ datasource.DataSource              = &NetworksApplianceSecurityMalwareDataSource{}
	_ datasource.DataSourceWithConfigure = &NetworksApplianceSecurityMalwareDataSource{}
)

func NewNetworksApplianceSecurityMalwareDataSource() datasource.DataSource {
	return &NetworksApplianceSecurityMalwareDataSource{}
}

type NetworksApplianceSecurityMalwareDataSource struct {
	client *merakigosdk.Client
}

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

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

func (d *NetworksApplianceSecurityMalwareDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
	resp.Schema = schema.Schema{
		Attributes: map[string]schema.Attribute{
			"network_id": schema.StringAttribute{
				MarkdownDescription: `networkId path parameter. Network ID`,
				Required:            true,
			},
			"item": schema.SingleNestedAttribute{
				Computed: true,
				Attributes: map[string]schema.Attribute{

					"allowed_files": schema.SetNestedAttribute{
						MarkdownDescription: `Sha256 digests of files permitted by the malware detection engine`,
						Computed:            true,
						NestedObject: schema.NestedAttributeObject{
							Attributes: map[string]schema.Attribute{

								"comment": schema.StringAttribute{
									MarkdownDescription: `Comment about the allowed file`,
									Computed:            true,
								},
								"sha256": schema.StringAttribute{
									MarkdownDescription: `The sha256 digest of allowed file`,
									Computed:            true,
								},
							},
						},
					},
					"allowed_urls": schema.SetNestedAttribute{
						MarkdownDescription: `URLs permitted by the malware detection engine`,
						Computed:            true,
						NestedObject: schema.NestedAttributeObject{
							Attributes: map[string]schema.Attribute{

								"comment": schema.StringAttribute{
									MarkdownDescription: `Comment about the allowed URL`,
									Computed:            true,
								},
								"url": schema.StringAttribute{
									MarkdownDescription: `The allowed URL`,
									Computed:            true,
								},
							},
						},
					},
					"mode": schema.StringAttribute{
						MarkdownDescription: `Current status of malware prevention`,
						Computed:            true,
					},
				},
			},
		},
	}
}

func (d *NetworksApplianceSecurityMalwareDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
	var networksApplianceSecurityMalware NetworksApplianceSecurityMalware
	diags := req.Config.Get(ctx, &networksApplianceSecurityMalware)
	if resp.Diagnostics.HasError() {
		return
	}

	selectedMethod := 1
	if selectedMethod == 1 {
		log.Printf("[DEBUG] Selected method: GetNetworkApplianceSecurityMalware")
		vvNetworkID := networksApplianceSecurityMalware.NetworkID.ValueString()

		// has_unknown_response: None

		response1, restyResp1, err := d.client.Appliance.GetNetworkApplianceSecurityMalware(vvNetworkID)

		if err != nil || response1 == nil {
			if restyResp1 != nil {
				log.Printf("[DEBUG] Retrieved error response %s", restyResp1.String())
			}
			resp.Diagnostics.AddError(
				"Failure when executing GetNetworkApplianceSecurityMalware",
				err.Error(),
			)
			return
		}

		networksApplianceSecurityMalware = ResponseApplianceGetNetworkApplianceSecurityMalwareItemToBody(networksApplianceSecurityMalware, response1)
		diags = resp.State.Set(ctx, &networksApplianceSecurityMalware)
		resp.Diagnostics.Append(diags...)
		if resp.Diagnostics.HasError() {
			return
		}

	}
}

// structs
type NetworksApplianceSecurityMalware struct {
	NetworkID types.String                                         `tfsdk:"network_id"`
	Item      *ResponseApplianceGetNetworkApplianceSecurityMalware `tfsdk:"item"`
}

type ResponseApplianceGetNetworkApplianceSecurityMalware struct {
	AllowedFiles *[]ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedFiles `tfsdk:"allowed_files"`
	AllowedURLs  *[]ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedUrls  `tfsdk:"allowed_urls"`
	Mode         types.String                                                       `tfsdk:"mode"`
}

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

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

// ToBody
func ResponseApplianceGetNetworkApplianceSecurityMalwareItemToBody(state NetworksApplianceSecurityMalware, response *merakigosdk.ResponseApplianceGetNetworkApplianceSecurityMalware) NetworksApplianceSecurityMalware {
	itemState := ResponseApplianceGetNetworkApplianceSecurityMalware{
		AllowedFiles: func() *[]ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedFiles {
			if response.AllowedFiles != nil {
				result := make([]ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedFiles, len(*response.AllowedFiles))
				for i, allowedFiles := range *response.AllowedFiles {
					result[i] = ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedFiles{
						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() *[]ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedUrls {
			if response.AllowedURLs != nil {
				result := make([]ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedUrls, len(*response.AllowedURLs))
				for i, allowedURLs := range *response.AllowedURLs {
					result[i] = ResponseApplianceGetNetworkApplianceSecurityMalwareAllowedUrls{
						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{}
		}(),
	}
	state.Item = &itemState
	return state
}
