package flattens

import (
	"context"

	"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/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/lb/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/lb/utilities"
)

func LBBackendResource(ctx context.Context, plan *models.ResourceLBBackendModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start flattens.LBBackendResource")

	diags := diag.Diagnostics{}

	recordItemBackend, diags := utilities.LBBackendResourceCheckPresence(ctx, plan, c)
	if diags.HasError() {
		return diags
	}

	*plan = models.ResourceLBBackendModel{
		LBID:      plan.LBID,
		Name:      plan.Name,
		ID:        plan.ID,
		Timeouts:  plan.Timeouts,
		GUID:      types.StringValue(recordItemBackend.GUID),
		Algorithm: types.StringValue(recordItemBackend.Algorithm),
		DownInter: types.Int64Value(int64(recordItemBackend.ServerDefaultSettings.DownInter)),
		Fall:      types.Int64Value(int64(recordItemBackend.ServerDefaultSettings.Fall)),
		Inter:     types.Int64Value(int64(recordItemBackend.ServerDefaultSettings.Inter)),
		MaxConn:   types.Int64Value(int64(recordItemBackend.ServerDefaultSettings.MaxConn)),
		MaxQueue:  types.Int64Value(int64(recordItemBackend.ServerDefaultSettings.MaxQueue)),
		Rise:      types.Int64Value(int64(recordItemBackend.ServerDefaultSettings.Rise)),
		SlowStart: types.Int64Value(int64(recordItemBackend.ServerDefaultSettings.SlowStart)),
		Weight:    types.Int64Value(int64(recordItemBackend.ServerDefaultSettings.Weight)),
		Servers:   flattenServersInLB(ctx, recordItemBackend.Servers),
	}

	tflog.Info(ctx, "End flattens.LBBackendResource", map[string]any{"name": plan.Name.ValueString()})
	return nil
}
