package utilities

import (
	"context"
	"regexp"

	"github.com/hashicorp/terraform-plugin-log/tflog"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/kvmvm/models"
)

func ComputeListCheckPresence(ctx context.Context, state *models.ListComputesModel, c *client.Client) (*compute.ListComputes, error) {
	tflog.Info(ctx, "Get compute list info")

	req := compute.ListRequest{}
	if !state.ByID.IsNull() {
		req.ByID = uint64(state.ByID.ValueInt64())
	}
	if !state.Name.IsNull() {
		req.Name = state.Name.ValueString()
	}
	if !state.AccountID.IsNull() {
		req.AccountID = uint64(state.AccountID.ValueInt64())
	}
	if !state.RGName.IsNull() {
		req.RGName = state.RGName.ValueString()
	}
	if !state.RGID.IsNull() {
		req.RGID = uint64(state.RGID.ValueInt64())
	}
	if !state.TechStatus.IsNull() {
		req.TechStatus = state.TechStatus.ValueString()
	}
	if !state.Status.IsNull() {
		req.Status = state.Status.ValueString()
	}
	if !state.IPAddress.IsNull() {
		req.IPAddress = state.IPAddress.ValueString()
	}
	if !state.ExtNetName.IsNull() {
		req.ExtNetName = state.ExtNetName.ValueString()
	}
	if !state.ExtNetID.IsNull() {
		req.ExtNetID = uint64(state.ExtNetID.ValueInt64())
	}
	if !state.IncludeDeleted.IsNull() {
		req.IncludeDeleted = state.IncludeDeleted.ValueBool()
	}
	if !state.SortBy.IsNull() {
		req.SortBy = state.SortBy.ValueString()
	}
	if !state.Page.IsNull() {
		req.Page = uint64(state.Page.ValueInt64())
	}
	if !state.Size.IsNull() {
		req.Size = uint64(state.Size.ValueInt64())
	}

	tflog.Info(ctx, "Check req", map[string]any{"req": req})

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

	if !state.IgnoreK8s.IsNull() && state.IgnoreK8s.ValueBool() {
		list = matchComputes(list)
	}

	tflog.Info(ctx, "Getting compute list info, successfully")
	return list, nil
}

func matchComputes(computeList *compute.ListComputes) *compute.ListComputes {
	matched, _ := regexp.Compile(`[a-zA-Z]+\\d+-[a-zA-Z]+\\d+-[a-zA-Z]+\\d+`)
	result := computeList.FilterFunc(func(ic compute.ItemCompute) bool {
		res := matched.Match([]byte(ic.Name))
		return !res
	})

	return &result
}
