package mssql

import (
	"fmt"
	"log"
	"time"

	"github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql"
	"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
	"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
	"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
	"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients"
	"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
	"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmMssqlServerVulnerabilityAssessment() *schema.Resource {
	return &schema.Resource{
		Create: resourceArmMssqlServerVulnerabilityAssessmentCreateUpdate,
		Read:   resourceArmMssqlServerVulnerabilityAssessmentRead,
		Update: resourceArmMssqlServerVulnerabilityAssessmentCreateUpdate,
		Delete: resourceArmMssqlServerVulnerabilityAssessmentDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

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

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

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

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

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

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

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

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

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

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

	resourceGroupName := policyId.ResourceGroup
	serverName := policyId.Path["servers"]
	policyClient := meta.(*clients.Client).MSSQL.ServerSecurityAlertPoliciesClient

	policy, err := policyClient.Get(ctx, resourceGroupName, serverName)
	if err != nil {
		return fmt.Errorf("Error retrieving Security Alert Policy: %+v", err)
	}
	if policy.State != sql.SecurityAlertPolicyStateEnabled {
		return fmt.Errorf("Security Alert Policy is not enabled")
	}

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

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

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

	props := vulnerabilityAssessment.ServerVulnerabilityAssessmentProperties

	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)
	}

	result, err := client.CreateOrUpdate(ctx, resourceGroupName, serverName, vulnerabilityAssessment)
	if err != nil {
		return fmt.Errorf("error updataing mssql server vulnerability assessment: %v", err)
	}

	if result.ID == nil {
		return fmt.Errorf("error reading mssql server vulnerability assessment id (server %q, resource group %q)", serverName, resourceGroupName)
	}

	d.SetId(*result.ID)

	return resourceArmMssqlServerVulnerabilityAssessmentRead(d, meta)
}

func resourceArmMssqlServerVulnerabilityAssessmentRead(d *schema.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 := azure.ParseAzureResourceID(d.Id())
	if err != nil {
		return err
	}

	resourceGroupName := id.ResourceGroup
	serverName := id.Path["servers"]

	result, err := client.Get(ctx, resourceGroupName, serverName)
	if err != nil {
		if utils.ResponseWasNotFound(result.Response) {
			log.Printf("[WARN] mssql server vulnerability assessment %v not found", id)
			d.SetId("")
			return nil
		}

		return fmt.Errorf("error making read request to mssql server vulnerability assessment: %+v", err)
	}

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

	if props := result.ServerVulnerabilityAssessmentProperties; 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 resourceArmMssqlServerVulnerabilityAssessmentDelete(d *schema.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 := azure.ParseAzureResourceID(d.Id())
	if err != nil {
		return err
	}

	resourceGroupName := id.ResourceGroup
	serverName := id.Path["servers"]

	if _, err = client.Delete(ctx, resourceGroupName, serverName); err != nil {
		return fmt.Errorf("error deleting mssql server vulnerability assessment: %v", err)
	}

	return nil
}

func expandRecurringScans(d *schema.ResourceData) *sql.VulnerabilityAssessmentRecurringScansProperties {
	props := sql.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 *sql.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}
}
