package flattens

import (
	"context"
	"encoding/json"
	"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 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:     types.Int64Value(int64(recordItemLB.RGID)),
		Name:     types.StringValue(recordItemLB.Name),
		ExtNetID: types.Int64Value(int64(recordItemLB.ExtNetID)),
		VINSID:   types.Int64Value(int64(recordItemLB.VINSID)),
		Start:    types.BoolValue(recordItemLB.TechStatus == "STARTED"),
		ID:       plan.ID,

		HAMode:       types.BoolValue(recordItemLB.HAMode),
		Safe:         plan.Safe,
		Timeouts:     plan.Timeouts,
		SysctlParams: plan.SysctlParams,
		Permanently:  plan.Permanently,
		Restore:      plan.Restore,
		Restart:      plan.Restart,
		Enable:       types.BoolValue(recordItemLB.Status == "ENABLED"),
		ConfigReset:  plan.ConfigReset,

		ACL:           types.StringValue(string(acl)),
		BackendHAIP:   types.StringValue(recordItemLB.BackendHAIP),
		Backends:      flattenBackendsInLB(ctx, recordItemLB.Backends),
		CreatedBy:     types.StringValue(recordItemLB.CreatedBy),
		CreatedTime:   types.Int64Value(int64(recordItemLB.CreatedTime)),
		DeletedBy:     types.StringValue(recordItemLB.DeletedBy),
		DeletedTime:   types.Int64Value(int64(recordItemLB.DeletedTime)),
		Description:   types.StringValue(recordItemLB.Description),
		DPAPIUser:     types.StringValue(recordItemLB.DPAPIUser),
		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)),
		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),
		RGName:        types.StringValue(recordItemLB.RGName),
		SecondaryNode: flattenNodeInLB(ctx, recordItemLB.SecondaryNode),
		Status:        types.StringValue(recordItemLB.Status),
		TechStatus:    types.StringValue(recordItemLB.TechStatus),
		UpdatedBy:     types.StringValue(recordItemLB.UpdatedBy),
		UpdatedTime:   types.Int64Value(int64(recordItemLB.UpdatedTime)),
		UserManaged:   types.BoolValue(recordItemLB.UserManaged),
	}

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

func flattenBackendsInLB(ctx context.Context, backends []lb.ItemBackend) types.List {
	tflog.Info(ctx, "Start flattenBackendsInLB")
	tempSlice := make([]types.Object, 0, len(backends))
	for _, backend := range backends {
		b := models.ItemBackendModel{
			Algorithm:             types.StringValue(backend.Algorithm),
			GUID:                  types.StringValue(backend.GUID),
			Name:                  types.StringValue(backend.Name),
			ServerDefaultSettings: flattenServersSettings(ctx, backend.ServerDefaultSettings),
			Servers:               flattenServersInLB(ctx, backend.Servers),
		}
		obj, diags := types.ObjectValueFrom(ctx, models.ItemBackend, b)
		if diags != nil {
			tflog.Error(ctx, fmt.Sprint("Error flattenBackendsInLB struct to obj", diags))
		}
		tempSlice = append(tempSlice, obj)
	}

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

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

func flattenFrontendsInLB(ctx context.Context, frontends []lb.ItemFrontend) types.List {
	tflog.Info(ctx, "Start flattenFrontendsInLB")
	tempSlice := make([]types.Object, 0, len(frontends))
	for _, frontend := range frontends {
		b := models.ItemFrontendModel{
			Backend:  types.StringValue(frontend.Backend),
			Bindings: flattenBindingsInLB(ctx, frontend.Bindings),
			GUID:     types.StringValue(frontend.GUID),
			Name:     types.StringValue(frontend.Name),
		}
		obj, diags := types.ObjectValueFrom(ctx, models.ItemFrontend, b)
		if diags != nil {
			tflog.Error(ctx, fmt.Sprint("Error flattenFrontendsInLB struct to obj", diags))
		}
		tempSlice = append(tempSlice, obj)
	}

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

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

func flattenNodeInLB(ctx context.Context, node lb.RecordNode) types.Object {
	tflog.Info(ctx, "Start flattenNodeInLB")
	n := models.RecordNodeModel{
		BackendIP:  types.StringValue(node.BackendIP),
		ComputeID:  types.Int64Value(int64(node.ComputeID)),
		FrontendIP: types.StringValue(node.FrontendIP),
		GUID:       types.StringValue(node.GUID),
		MGMTIP:     types.StringValue(node.MGMTIP),
		NetworkID:  types.Int64Value(int64(node.NetworkID)),
	}
	obj, diags := types.ObjectValueFrom(ctx, models.ItemNode, n)
	if diags != nil {
		tflog.Error(ctx, fmt.Sprint("Error flattenNodeInLB struct to obj", diags))
	}
	tflog.Info(ctx, "End flattenNodeInLB")
	return obj
}
