package image

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/compute"
	"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{}

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

	return len(accounts.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 existComputeID(ctx context.Context, computeId uint64, m interface{}) error {
	c := m.(*controller.ControllerCfg)
	req := compute.GetRequest{ComputeID: computeId}

	// check for compute existence
	computeRecord, err := c.CloudAPI().Compute().Get(ctx, req)
	if err != nil {
		return fmt.Errorf("ComputeID %d is not allowed or does not exist", computeId)
	}

	// check if compute was created as blank
	computeImageId := computeRecord.ImageID
	bootImageId := -1
	for _, d := range computeRecord.Disks {
		if computeRecord.Chipset == "i440fx" {
			if d.PCISlot == 6 {
				bootImageId = int(d.ImageID)
				break
			}
		} else {
			if d.BusNumber == 6 {
				bootImageId = int(d.ImageID)
				break
			}
		}
	}

	if computeImageId != 0 && bootImageId != 0 {
		return fmt.Errorf("ComputeID %d is not allowed because it is not blank compute (either compute imageId or boot imageId are not zero)", computeId)
	}

	return 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) != 1 {
		return fmt.Errorf("diskId %d is not allowed or doesn't exist", diskId)
	}

	return nil
}
