package disks

import (
	"context"
	"fmt"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/locations"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)

func existAccountID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
	c := m.(*controller.ControllerCfg)
	accountId := uint64(d.Get("account_id").(int))
	req := account.ListRequest{}

	accountList, err := c.CloudAPI().Account().List(ctx, req)
	if err != nil {
		return false, err
	}

	return len(accountList.FilterByID(accountId).Data) != 0, nil
}

func existGID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
	c := m.(*controller.ControllerCfg)
	gid := uint64(d.Get("gid").(int))
	req := locations.ListRequest{}

	locationList, err := c.CloudAPI().Locations().List(ctx, req)
	if err != nil {
		return false, err
	}

	return len(locationList.FilterByGID(gid).Data) != 0, nil
}

func existDiskID(ctx context.Context, diskId uint64, m interface{}) error {
	c := m.(*controller.ControllerCfg)

	req := disks.ListRequest{
		ByID: diskId,
	}

	diskList, err := c.CloudAPI().Disks().List(ctx, req)
	if err != nil {
		return err
	}

	if len(diskList.Data) == 0 {
		return fmt.Errorf("resourceDiskReplication: can't create or update Disk replication because DiskID %d is not allowed or does not exist", diskId)
	}

	if diskList.Data[0].SepType != "TATLIN" {
		return fmt.Errorf("resourceDiskReplication: can't create or update Disk replication because DiskID %d is not TATLIN SEP Type", diskId)
	}

	return nil
}
