package trunk

import (
	"context"
	"strconv"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	log "github.com/sirupsen/logrus"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/trunk"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)

func utilityTrunkCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*trunk.ItemTrunk, error) {
	c := m.(*controller.ControllerCfg)
	req := trunk.GetRequest{}

	if d.Id() != "" {
		id, err := strconv.ParseInt(d.Id(), 10, 64)
		if err != nil {
			return nil, err
		}

		req.TrunkID = uint64(id)
	} else {
		req.TrunkID = uint64(d.Get("trunk_id").(int))
	}

	trunkInfo, err := c.CloudBroker().Trunk().Get(ctx, req)
	if err != nil {
		return nil, err
	}

	return trunkInfo, nil
}

func handleAccountAccessUpdate(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg, trnk *trunk.ItemTrunk) error {
	oldSet, newSet := d.GetChange("account_ids")

	revokeSet := oldSet.(*schema.Set).Difference(newSet.(*schema.Set))
	if revokeSet.Len() > 0 {
		accountIDs := make([]uint64, 0)
		for _, revokeAccountID := range revokeSet.List() {
			accountIDs = append(accountIDs, uint64(revokeAccountID.(int)))
		}

		log.Debugf("cloudbroker: revoking access from %d account IDs", revokeSet.Len())

		req := trunk.AccessRevokeRequest{
			TrunkID:    trnk.ID,
			AccountIDs: accountIDs,
		}

		_, err := c.CloudBroker().Trunk().AccessRevoke(ctx, req)
		if err != nil {
			return err
		}
	}

	grantSet := newSet.(*schema.Set).Difference(oldSet.(*schema.Set))
	if grantSet.Len() > 0 {
		accountIDs := make([]uint64, 0)
		for _, grantAccountID := range grantSet.List() {
			accountIDs = append(accountIDs, uint64(grantAccountID.(int)))
		}

		log.Debugf("cloudbroker: granting access to %d account IDs", grantSet.Len())

		req := trunk.AccessGrantRequest{
			TrunkID:    trnk.ID,
			AccountIDs: accountIDs,
		}

		_, err := c.CloudBroker().Trunk().AccessGrant(ctx, req)
		if err != nil {
			return err
		}
	}

	return nil
}

func handleTrunkEnabling(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg, trunkID uint64) error {
	if d.Get("enable").(bool) {
		req := trunk.EnableRequest{
			TrunkID: trunkID,
		}

		_, err := c.CloudBroker().Trunk().Enable(ctx, req)
		if err != nil {
			return err
		}
	} else {
		req := trunk.DisableRequest{
			TrunkID: trunkID,
		}

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

	return nil
}
