package utilities

import (
	"context"
	"fmt"

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

func FlipgroupListDataSourceCheckPresence(ctx context.Context, plan *models.DataSourceFLIPGroupModelList, c *client.Client) (*flipgroup.ListFLIPGroups, diag.Diagnostics) {
	tflog.Info(ctx, fmt.Sprintf("FlipgroupListDataSourceCheckPresence: Get info about flipgroup list"))

	diags := diag.Diagnostics{}

	listFlipgroupReq := flipgroup.ListRequest{}
	if !plan.Name.IsNull() {
		listFlipgroupReq.Name = plan.Name.ValueString()
	}

	if !plan.VinsID.IsNull() {
		listFlipgroupReq.VINSID = uint64(plan.VinsID.ValueInt64())
	}

	if !plan.VinsName.IsNull() {
		listFlipgroupReq.VINSName = plan.VinsName.ValueString()
	}

	if !plan.ExtnetID.IsNull() {
		listFlipgroupReq.ExtNetID = uint64(plan.ExtnetID.ValueInt64())
	}

	if !plan.ByIP.IsNull() {
		listFlipgroupReq.ByIP = plan.ByIP.ValueString()
	}

	if !plan.AccountID.IsNull() {
		listFlipgroupReq.AccountId = uint64(plan.AccountID.ValueInt64())
	}

	if !plan.RgID.IsNull() {
		listFlipgroupReq.RGID = uint64(plan.RgID.ValueInt64())
	}

	if !plan.FlipgroupID.IsNull() {
		listFlipgroupReq.ByID = uint64(plan.FlipgroupID.ValueInt64())
	}

	if !plan.Page.IsNull() {
		listFlipgroupReq.Page = uint64(plan.Page.ValueInt64())
	}

	if !plan.Size.IsNull() {
		listFlipgroupReq.Size = uint64(plan.Size.ValueInt64())
	}

	if !plan.ConnID.IsNull() {
		listFlipgroupReq.ConnId = uint64(plan.ConnID.ValueInt64())
	}

	if !plan.CliendIDs.IsNull() {
		result := make([]uint64, 0, len(plan.CliendIDs.Elements()))
		for _, val := range plan.CliendIDs.Elements() {
			result = append(result, uint64(val.(types.Int64).ValueInt64()))
		}
		//TODO fix it
		//listFlipgroupReq.ClientIDs = result
	}

	if !plan.Status.IsNull() {
		listFlipgroupReq.Status = plan.Status.ValueString()
	}

	if !plan.SortBy.IsNull() {
		listFlipgroupReq.SortBy = plan.SortBy.ValueString()
	}

	recordFG, err := c.CloudAPI().FLIPGroup().List(ctx, listFlipgroupReq)
	if err != nil {
		diags.AddError(fmt.Sprintf("FlipgroupDataSourceCheckPresence: Cannot get info about flipgroup list"), err.Error())
		return nil, diags
	}

	tflog.Info(ctx, "FlipgroupDataSourceCheckPresence: successfull response from CloudAPI().FLIPGroup().List")

	return recordFG, nil
}
