package vins

import (
	"context"

	"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/extnet"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/locations"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/rg"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vins"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)

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

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

	return len(rgList.FilterByID(rgId).Data) != 0, nil
}

func existExtNetID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
	extNetID := d.Get("ext_net_id").(int)

	if extNetID == 0 || extNetID == -1 {
		return true, nil
	}

	c := m.(*controller.ControllerCfg)
	extNetIDParsed := uint64(extNetID)
	req := extnet.ListRequest{}

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

	return len(extNetList.FilterByID(extNetIDParsed).Data) != 0, nil
}

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 existVinsID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
	c := m.(*controller.ControllerCfg)
	vinsID := uint64(d.Get("vins_id").(int))
	req := vins.ListRequest{}

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

	return len(vinsList.FilterByID(vinsID).Data) != 0, nil
}
