/*
Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>

Licensed under the Apache 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

    http://www.apache.org/licenses/LICENSE-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.
*/

/*
Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud
Orchestration Technology) with Terraform by Hashicorp.

Source code: https://repository.basistech.ru/BASIS/terraform-provider-decort

Please see README.md to learn where to place source code so that it
builds seamlessly.

Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/

package pcidevice

import (
	"context"
	"strconv"

	log "github.com/sirupsen/logrus"

	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/pcidevice"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/dc"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/status"
)

func resourcePcideviceCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourcePcideviceCreate: called for pcidevice %s", d.Get("name").(string))

	c := m.(*controller.ControllerCfg)
	createReq := pcidevice.CreateRequest{}

	if diags := checkParamsExistence(ctx, d, c); diags != nil {
		return diags
	}

	createReq.NodeID = uint64(d.Get("node_id").(int))
	createReq.RGID = uint64(d.Get("rg_id").(int))
	createReq.Name = d.Get("name").(string)
	createReq.HWPath = d.Get("hw_path").(string)

	if description, ok := d.GetOk("description"); ok {
		createReq.Description = description.(string)
	}

	pcideviceId, err := c.CloudBroker().PCIDevice().Create(ctx, createReq)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	d.SetId(strconv.FormatUint(pcideviceId, 10))
	d.Set("device_id", pcideviceId)

	warnings := dc.Warnings{}

	if enable, ok := d.GetOk("enable"); ok {
		log.Debugf("resourcePcideviceCreate: enable=%t device_id %d after completing its resource configuration", enable, pcideviceId)

		if enable.(bool) {
			req := pcidevice.EnableRequest{DeviceID: pcideviceId}
			if _, err := c.CloudBroker().PCIDevice().Enable(ctx, req); err != nil {
				warnings.Add(err)
			}

		} else {
			req := pcidevice.DisableRequest{
				DeviceID: pcideviceId,
			}
			if force, ok := d.GetOk("force_disable"); ok {
				req.Force = force.(bool)
				log.Debugf("force_disable=%v", force)
			}
			if _, err := c.CloudBroker().PCIDevice().Disable(ctx, req); err != nil {
				warnings.Add(err)
			}
		}
	}

	return append(resourcePcideviceRead(ctx, d, m), warnings.Get()...)
}

func resourcePcideviceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourcePcideviceRead: called for pci_device id %d, name %s",
		d.Id(), d.Get("name").(string))

	pcideviceRec, err := utilityPcideviceCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	flattenPcidevice(d, pcideviceRec)

	log.Debugf("resourcePcideviceRead: after flattenPcidevice: device_id %s, name %s",
		d.Id(), d.Get("name").(string))

	return nil
}

func resourcePcideviceUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourcePcideviceUpdate: called for pcidevice id %s, name %s", d.Id(), d.Get("name").(string))

	c := m.(*controller.ControllerCfg)

	if diags := checkParamsExistence(ctx, d, c); diags != nil {
		return diags
	}

	if d.HasChange("enable") {
		err := resourcePcideviceChangeEnable(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}
	}

	return resourcePcideviceRead(ctx, d, m)
}

func resourcePcideviceDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourcePcideviceDelete: called for %s, id: %s", d.Get("name").(string), d.Id())

	c := m.(*controller.ControllerCfg)

	pciDevice, err := utilityPcideviceCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	if pciDevice.Status == status.Destroyed || pciDevice.Status == status.Purged {
		return nil
	}

	req := pcidevice.DeleteRequest{
		DeviceID: pciDevice.ID,
	}
	if force, ok := d.GetOk("force_delete"); ok {
		req.Force = force.(bool)
	}

	if _, err = c.CloudBroker().PCIDevice().Delete(ctx, req); err != nil {
		return diag.FromErr(err)
	}

	d.SetId("")

	return nil
}

func ResourcePcidevice() *schema.Resource {
	return &schema.Resource{
		SchemaVersion: 1,

		CreateContext: resourcePcideviceCreate,
		ReadContext:   resourcePcideviceRead,
		UpdateContext: resourcePcideviceUpdate,
		DeleteContext: resourcePcideviceDelete,

		Importer: &schema.ResourceImporter{
			StateContext: schema.ImportStatePassthroughContext,
		},

		Timeouts: &schema.ResourceTimeout{
			Create:  &constants.Timeout900s,
			Read:    &constants.Timeout300s,
			Update:  &constants.Timeout300s,
			Delete:  &constants.Timeout300s,
			Default: &constants.Timeout300s,
		},

		Schema: resourcePcideviceSchemaMake(),
	}
}

func resourcePcideviceChangeEnable(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	enable := d.Get("enable").(bool)
	log.Debugf("resourcePcideviceChangeEnable: enable=%t device_id %s after completing its resource configuration", enable, d.Id())

	pcideviceRec, err := utilityPcideviceCheckPresence(ctx, d, m)
	if err != nil {
		return err
	}
	c := m.(*controller.ControllerCfg)

	if enable {
		req := pcidevice.EnableRequest{
			DeviceID: pcideviceRec.ID,
		}

		if _, err := c.CloudBroker().PCIDevice().Enable(ctx, req); err != nil {
			return err
		}
	} else {
		req := pcidevice.DisableRequest{
			DeviceID: pcideviceRec.ID,
		}
		if force, ok := d.GetOk("force_disable"); ok {
			req.Force = force.(bool)
		}

		if _, err := c.CloudBroker().PCIDevice().Disable(ctx, req); err != nil {
			return err
		}
	}

	return nil
}
