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/cloudbroker/lb"
	"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"
)

// LBDataSource flattens data source for lb.
// Return error in case data source is not found on the platform.
// Flatten errors are added to tflog.
func LBDataSource(ctx context.Context, state *models.DataSourceLB, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start flattens.LBDataSource")

	diags := diag.Diagnostics{}

	lbID := uint64(state.LBID.ValueInt64())

	recordLB, diags := utilities.LBDataSourceCheckPresence(ctx, lbID, c)
	if diags.HasError() {
		return diags
	}

	tflog.Info(ctx, "flattens.LBDataSource: before flatten", map[string]any{"lb_id": lbID})

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

	*state = models.DataSourceLB{
		LBID:     state.LBID,
		Timeouts: state.Timeouts,

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

	tflog.Info(ctx, "End flattens.LBDataSource", map[string]any{"lb_id": state.ID.ValueInt64()})
	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.Node) 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
}

func flattenServersSettings(ctx context.Context, settings lb.ServerSettings) types.Object {
	tflog.Info(ctx, "Start flattenServersSettings")
	s := models.RecordServerSettingsModel{
		Inter:     types.Int64Value(int64(settings.Inter)),
		GUID:      types.StringValue(settings.GUID),
		DownInter: types.Int64Value(int64(settings.DownInter)),
		Rise:      types.Int64Value(int64(settings.Rise)),
		Fall:      types.Int64Value(int64(settings.Fall)),
		SlowStart: types.Int64Value(int64(settings.SlowStart)),
		MaxConn:   types.Int64Value(int64(settings.MaxConn)),
		MaxQueue:  types.Int64Value(int64(settings.MaxQueue)),
		Weight:    types.Int64Value(int64(settings.Weight)),
	}
	obj, diags := types.ObjectValueFrom(ctx, models.ItemServerSettings, s)
	if diags != nil {
		tflog.Error(ctx, fmt.Sprint("Error flattenServersSettings struct to obj", diags))
	}
	tflog.Info(ctx, "End flattenServersSettings")
	return obj
}

func flattenServersInLB(ctx context.Context, servers []lb.ItemServer) types.List {
	tflog.Info(ctx, "Start flattenServersInLBBackend")
	tempSlice := make([]types.Object, 0, len(servers))
	for _, server := range servers {
		s := models.RecordServerModel{
			Address:        types.StringValue(server.Address),
			Check:          types.StringValue(server.Check),
			GUID:           types.StringValue(server.GUID),
			Name:           types.StringValue(server.Name),
			Port:           types.Int64Value(int64(server.Port)),
			ServerSettings: flattenServersSettings(ctx, server.ServerSettings),
		}
		obj, diags := types.ObjectValueFrom(ctx, models.ItemServers, s)
		if diags != nil {
			tflog.Error(ctx, fmt.Sprint("Error flattenServersInLBBackend struct to obj", diags))
		}
		tempSlice = append(tempSlice, obj)
	}

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

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

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
}
