// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package mssql

import (
	"fmt"
	"log"
	"time"

	"github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v5.0/sql" // nolint: staticcheck
	"github.com/hashicorp/go-azure-helpers/lang/response"
	"github.com/hashicorp/go-azure-helpers/resourcemanager/commonids"
	"github.com/hashicorp/go-azure-sdk/resource-manager/sql/2023-08-01-preview/servervulnerabilityassessments"
	"github.com/hashicorp/terraform-provider-azurerm/helpers/azure"
	"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
	"github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/parse"
	"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
	"github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation"
	"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
	"github.com/hashicorp/terraform-provider-azurerm/utils"
)

func resourceMsSqlServerVulnerabilityAssessment() *pluginsdk.Resource {
	return &pluginsdk.Resource{
		Create: resourceMsSqlServerVulnerabilityAssessmentCreateUpdate,
		Read:   resourceMsSqlServerVulnerabilityAssessmentRead,
		Update: resourceMsSqlServerVulnerabilityAssessmentCreateUpdate,
		Delete: resourceMsSqlServerVulnerabilityAssessmentDelete,

		Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
			_, err := parse.ServerVulnerabilityAssessmentID(id)
			return err
		}),

		Timeouts: &pluginsdk.ResourceTimeout{
			Create: pluginsdk.DefaultTimeout(30 * time.Minute),
			Read:   pluginsdk.DefaultTimeout(5 * time.Minute),
			Update: pluginsdk.DefaultTimeout(30 * time.Minute),
			Delete: pluginsdk.DefaultTimeout(30 * time.Minute),
		},

		Schema: map[string]*pluginsdk.Schema{
			"server_security_alert_policy_id": {
				Type:         pluginsdk.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: azure.ValidateResourceID,
			},

			"storage_container_path": {
				Type:         pluginsdk.TypeString,
				Required:     true,
				ValidateFunc: validation.StringIsNotEmpty,
			},

			"recurring_scans": {
				Type:     pluginsdk.TypeList,
				Optional: true,
				Computed: true,
				MaxItems: 1,
				Elem: &pluginsdk.Resource{
					Schema: map[string]*pluginsdk.Schema{
						"email_subscription_admins": {
							Type:     pluginsdk.TypeBool,
							Optional: true,
							Default:  false,
						},

						"emails": {
							Type:     pluginsdk.TypeList,
							Optional: true,
							Elem: &pluginsdk.Schema{
								Type:         pluginsdk.TypeString,
								ValidateFunc: validation.StringIsNotEmpty,
							},
						},

						"enabled": {
							Type:     pluginsdk.TypeBool,
							Optional: true,
							Default:  false,
						},
					},
				},
			},

			"storage_account_access_key": {
				Type:         pluginsdk.TypeString,
				Optional:     true,
				Sensitive:    true,
				ValidateFunc: validation.StringIsNotEmpty,
			},

			"storage_container_sas_key": {
				Type:         pluginsdk.TypeString,
				Optional:     true,
				Sensitive:    true,
				ValidateFunc: validation.StringIsNotEmpty,
			},
		},
	}
}

func resourceMsSqlServerVulnerabilityAssessmentCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
	client := meta.(*clients.Client).MSSQL.ServerVulnerabilityAssessmentsClient
	ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
	defer cancel()

	policyId, err := parse.ServerSecurityAlertPolicyID(d.Get("server_security_alert_policy_id").(string))
	if err != nil {
		return err
	}

	policyClient := meta.(*clients.Client).MSSQL.LegacyServerSecurityAlertPoliciesClient

	policy, err := policyClient.Get(ctx, policyId.ResourceGroup, policyId.ServerName)
	if err != nil {
		return fmt.Errorf("retrieving Security Alert Policy: %+v", err)
	}
	if policy.State != sql.SecurityAlertsPolicyStateEnabled {
		return fmt.Errorf("security alert policy is not enabled")
	}

	log.Printf("[INFO] preparing arguments for mssql server vulnerability assessment creation.")

	id := parse.NewServerVulnerabilityAssessmentID(policyId.SubscriptionId, policyId.ResourceGroup, policyId.ServerName, "default")

	storageContainerPath := d.Get("storage_container_path").(string)

	vulnerabilityAssessment := servervulnerabilityassessments.ServerVulnerabilityAssessment{
		Properties: &servervulnerabilityassessments.ServerVulnerabilityAssessmentProperties{
			StorageContainerPath: storageContainerPath,
		},
	}

	props := vulnerabilityAssessment.Properties

	if v, ok := d.GetOk("storage_account_access_key"); ok {
		props.StorageAccountAccessKey = utils.String(v.(string))
	}

	if v, ok := d.GetOk("storage_container_sas_key"); ok {
		props.StorageContainerSasKey = utils.String(v.(string))
	}

	if _, ok := d.GetOk("recurring_scans"); ok {
		props.RecurringScans = expandRecurringScans(d)
	}

	serverId := commonids.NewSqlServerID(id.SubscriptionId, id.ResourceGroup, id.ServerName)

	result, err := client.CreateOrUpdate(ctx, serverId, vulnerabilityAssessment)
	if err != nil {
		return fmt.Errorf("updating %s : %v", id, err)
	}

	if result.Model == nil || result.Model.Id == nil {
		return fmt.Errorf("reading %s", id)
	}

	d.SetId(id.ID())

	return resourceMsSqlServerVulnerabilityAssessmentRead(d, meta)
}

func resourceMsSqlServerVulnerabilityAssessmentRead(d *pluginsdk.ResourceData, meta interface{}) error {
	client := meta.(*clients.Client).MSSQL.ServerVulnerabilityAssessmentsClient
	ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
	defer cancel()

	log.Printf("[INFO] reading mssql server vulnerability assessment")

	id, err := parse.ServerVulnerabilityAssessmentID(d.Id())
	if err != nil {
		return err
	}

	serverId := commonids.NewSqlServerID(id.SubscriptionId, id.ResourceGroup, id.ServerName)

	result, err := client.Get(ctx, serverId)
	if err != nil {
		if response.WasNotFound(result.HttpResponse) {
			log.Printf("[WARN] mssql server vulnerability assessment %v not found", id)
			d.SetId("")
			return nil
		}

		return fmt.Errorf("retrieving %s: %+v", *id, err)
	}

	policyClient := meta.(*clients.Client).MSSQL.LegacyServerSecurityAlertPoliciesClient
	policy, err := policyClient.Get(ctx, id.ResourceGroup, id.ServerName)
	if err != nil {
		return fmt.Errorf("retrieving Security Alert Policy by ID: %+v", err)
	}
	d.Set("server_security_alert_policy_id", policy.ID)

	if model := result.Model; model != nil {
		if props := model.Properties; props != nil {
			d.Set("storage_container_path", props.StorageContainerPath)

			if v, ok := d.GetOk("storage_account_access_key"); ok {
				d.Set("storage_account_access_key", v)
			}

			if v, ok := d.GetOk("storage_container_sas_key"); ok {
				d.Set("storage_container_sas_key", v)
			}

			if props.RecurringScans != nil {
				d.Set("recurring_scans", flattenRecurringScans(props.RecurringScans))
			}
		}
	}
	return nil
}

func resourceMsSqlServerVulnerabilityAssessmentDelete(d *pluginsdk.ResourceData, meta interface{}) error {
	client := meta.(*clients.Client).MSSQL.ServerVulnerabilityAssessmentsClient
	ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
	defer cancel()

	log.Printf("[INFO] deleting mssql server vulnerability assessment.")

	id, err := parse.ServerVulnerabilityAssessmentID(d.Id())
	if err != nil {
		return err
	}

	serverId := commonids.NewSqlServerID(id.SubscriptionId, id.ResourceGroup, id.ServerName)

	if _, err = client.Delete(ctx, serverId); err != nil {
		return fmt.Errorf("deleting %s: %v", *id, err)
	}

	return nil
}

func expandRecurringScans(d *pluginsdk.ResourceData) *servervulnerabilityassessments.VulnerabilityAssessmentRecurringScansProperties {
	props := servervulnerabilityassessments.VulnerabilityAssessmentRecurringScansProperties{}

	vs := d.Get("recurring_scans").([]interface{})
	if len(vs) == 0 {
		return &props
	}

	v := vs[0].(map[string]interface{})

	if enabled, ok := v["enabled"]; ok {
		props.IsEnabled = utils.Bool(enabled.(bool))
	}

	if emailSubscriptionAdmins, ok := v["email_subscription_admins"]; ok {
		props.EmailSubscriptionAdmins = utils.Bool(emailSubscriptionAdmins.(bool))
	}

	if _, ok := v["emails"]; ok {
		emails := make([]string, 0)
		for _, uri := range v["emails"].([]interface{}) {
			emails = append(emails, uri.(string))
		}
		props.Emails = &emails
	}

	return &props
}

func flattenRecurringScans(props *servervulnerabilityassessments.VulnerabilityAssessmentRecurringScansProperties) []interface{} {
	result := make(map[string]interface{})

	if enabled := props.IsEnabled; enabled != nil {
		result["enabled"] = *props.IsEnabled
	}

	if emailSubscriptionAdmins := props.EmailSubscriptionAdmins; emailSubscriptionAdmins != nil {
		result["email_subscription_admins"] = *props.EmailSubscriptionAdmins
	}

	if props.Emails != nil {
		result["emails"] = *props.Emails
	}

	return []interface{}{result}
}
