package flattens

import (
	"context"
	"encoding/json"

	"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/flattens"
	"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 LBResource(ctx context.Context, plan *models.ResourceLBModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start flattens.LBResource")

	diags := diag.Diagnostics{}

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

	acl, _ := json.Marshal(recordItemLB.ACL)

	*plan = models.ResourceLBModel{
		RGID:     plan.RGID,
		Name:     plan.Name,
		ExtNetID: plan.ExtNetID,
		VINSID:   plan.VINSID,
		Start:    plan.Start,
		ID:       plan.ID,

		HAMode:       types.BoolValue(recordItemLB.HAMode),
		Safe:         plan.Safe,
		Timeouts:     plan.Timeouts,
		SysctlParams: plan.SysctlParams,
		Permanently:  plan.Permanently,
		Restart:      plan.Restart,
		Enable:       plan.Enable,
		ConfigReset:  plan.ConfigReset,

		ACL:           types.StringValue(string(acl)),
		BackendHAIP:   types.StringValue(recordItemLB.BackendHAIP),
		Backends:      flattenBackendsInLB(ctx, recordItemLB.Backends),
		CKey:          types.StringValue(recordItemLB.CKey),
		Description:   types.StringValue(recordItemLB.Description),
		DPAPIUser:     types.StringValue(recordItemLB.DPAPIUser),
		DPAPIPassword: types.StringValue(recordItemLB.DPAPIPassword),
		FrontendHAIP:  types.StringValue(recordItemLB.FrontendHAIP),
		Frontends:     flattenFrontendsInLB(ctx, recordItemLB.Frontends),
		GID:           types.Int64Value(int64(recordItemLB.GID)),
		GUID:          types.Int64Value(int64(recordItemLB.GUID)),
		ImageID:       types.Int64Value(int64(recordItemLB.ImageID)),
		LBID:          types.Int64Value(int64(recordItemLB.ID)),
		Meta:          flattens.FlattenSimpleTypeToList(ctx, types.StringType, &recordItemLB.Meta),
		Milestones:    types.Int64Value(int64(recordItemLB.Milestones)),
		ManagerId:     types.Int64Value(int64(recordItemLB.ManagerId)),
		ManagerType:   types.StringValue(recordItemLB.ManagerType),
		PartK8s:       types.BoolValue(recordItemLB.PartK8s),
		PrimaryNode:   flattenNodeInLB(ctx, recordItemLB.PrimaryNode),
		SecondaryNode: flattenNodeInLB(ctx, recordItemLB.SecondaryNode),
		Status:        types.StringValue(recordItemLB.Status),
		TechStatus:    types.StringValue(recordItemLB.TechStatus),
		UserManaged:   types.BoolValue(recordItemLB.UserManaged),
	}

	tflog.Info(ctx, "End flattens.LBResource", map[string]any{"id": plan.ID.ValueString()})
	return nil
}
