package flattens

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

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

	diags := diag.Diagnostics{}

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

	*plan = models.ResourceLBFrontendModel{
		LBID:     plan.LBID,
		Name:     types.StringValue(recordItemFrontend.Name),
		Backend:  plan.Backend,
		ID:       plan.ID,
		Timeouts: plan.Timeouts,
		GUID:     types.StringValue(recordItemFrontend.GUID),
		Bindings: flattenBindingsInLB(ctx, recordItemFrontend.Bindings),
	}

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

func flattenBindingsInLB(ctx context.Context, bindings []lb.ItemBinding) types.List {
	tflog.Info(ctx, "Start flattenBindingsInLBFrontend")
	tempSlice := make([]types.Object, 0, len(bindings))
	for _, binding := range bindings {
		s := models.ItemBindingModel{
			Address: types.StringValue(binding.Address),
			GUID:    types.StringValue(binding.GUID),
			Name:    types.StringValue(binding.Name),
			Port:    types.Int64Value(int64(binding.Port)),
		}
		obj, diags := types.ObjectValueFrom(ctx, models.ItemBindings, s)
		if diags != nil {
			tflog.Error(ctx, fmt.Sprint("Error flattenBindingsInLBFrontend struct to obj", diags))
		}
		tempSlice = append(tempSlice, obj)
	}

	res, diags := types.ListValueFrom(ctx, types.ObjectType{AttrTypes: models.ItemBindings}, tempSlice)
	if diags != nil {
		tflog.Error(ctx, fmt.Sprint("Error flattenBindingsInLBFrontend", diags))
	}

	tflog.Info(ctx, "End flattenBindingsInLBFrontend")
	return res
}
