package utilities

import (
	"context"
	"fmt"

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

func DPDKListDataSourceCheckPresence(ctx context.Context, plan *models.DataSourceDPDKListModel, c *client.Client) (*dpdknet.ListDPDKNet, error) {
	tflog.Info(ctx, fmt.Sprintf("DPDKListDataSourceCheckPresence: Get DPDK list info"))

	listDPDKReq := dpdknet.ListRequest{}

	if !plan.ByID.IsNull() {
		listDPDKReq.ByID = uint64(plan.ByID.ValueInt64())
	}
	if !plan.GID.IsNull() {
		listDPDKReq.GID = uint64(plan.GID.ValueInt64())
	}
	if !plan.Name.IsNull() {
		listDPDKReq.Name = plan.Name.ValueString()
	}
	if !plan.Desc.IsNull() {
		listDPDKReq.Description = plan.Desc.ValueString()
	}
	if !plan.Status.IsNull() {
		listDPDKReq.Status = plan.Status.ValueString()
	}
	if !plan.ComputeIDs.IsNull() {
		computeIDs := make([]uint64, 0, len(plan.ComputeIDs.Elements()))
		diags := plan.ComputeIDs.ElementsAs(ctx, &computeIDs, false)
		if diags.HasError() {
			tflog.Error(ctx, "DPDKListDataSourceCheckPresence: cannot populate computeIDs with plan.ComputeIDs List elements")
			return nil, fmt.Errorf("cannot populate computeIDs with plan.ComputeIDs List elements")
		}
		listDPDKReq.ComputeIDs = computeIDs
	}
	if !plan.SortBy.IsNull() {
		listDPDKReq.SortBy = plan.SortBy.ValueString()
	}
	if !plan.Page.IsNull() {
		listDPDKReq.Page = uint64(plan.Page.ValueInt64())
	}
	if !plan.Size.IsNull() {
		listDPDKReq.Size = uint64(plan.Size.ValueInt64())
	}

	tflog.Info(ctx, "DPDKListDataSourceCheckPresence: before call CloudAPI().DPDKNet().List", map[string]any{"response": listDPDKReq})
	dpdkList, err := c.CloudAPI().DPDKNet().List(ctx, listDPDKReq)
	if err != nil {
		return nil, fmt.Errorf("cannot get info about data source list DPDK net with error: %w", err)
	}

	tflog.Info(ctx, "DPDKListDataSourceCheckPresence: response from CloudAPI().DPDKNet().List", map[string]any{"response": dpdkList})

	return dpdkList, err
}
