package utilities

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"github.com/hashicorp/terraform-plugin-framework/diag"
	"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/service/cloudbroker/lb/models"
)

func CreateResourceLBFrontendBind(ctx context.Context, plan *models.ResourceLBFrontendBindModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, fmt.Sprintf("Start create ResourceLBFrontendBind: frontend_name %s", plan.Name.ValueString()))

	diags := diag.Diagnostics{}

	createReq := lb.FrontendBindRequest{
		LBID:           uint64(plan.LBID.ValueInt64()),
		FrontendName:   plan.Frontend.ValueString(),
		BindingName:    plan.Name.ValueString(),
		BindingAddress: plan.Address.ValueString(),
		BindingPort:    uint64(plan.Port.ValueInt64()),
	}

	tflog.Info(ctx, "ResourceLBFrontendBind: before call CloudBroker().LB().FrontendBind", map[string]any{"req": createReq})

	resp, err := c.CloudBroker().LB().FrontendBind(ctx, createReq)
	if err != nil {
		diags.AddError("ResourceLBFrontendBind: unable to create LB Frontend Bind", err.Error())
		return diags
	}
	tflog.Info(ctx, "ResourceLBFrontendBind: LB Frontend Bind created", map[string]any{"responce": resp, "name": plan.Name.ValueString()})

	return nil
}

func LBFrontendBindResourceCheckPresence(ctx context.Context, plan *models.ResourceLBFrontendBindModel, c *client.Client) (*lb.ItemBinding, diag.Diagnostics) {
	tflog.Info(ctx, fmt.Sprintf("LBFrontendBindCheckPresence: Get info about LB Frontend Bind with ID - %v", plan.ID.ValueString()))

	diags := diag.Diagnostics{}
	req := lb.GetRequest{}
	fName := plan.Frontend.ValueString()
	bName := plan.Name.ValueString()

	if !plan.LBID.IsNull() {
		req.LBID = uint64(plan.LBID.ValueInt64())
	} else {
		parameters := strings.Split(plan.ID.ValueString(), "#")
		if len(parameters) != 3 {
			diags.AddError("LBFrontendResourceCheckPresence: broken state id",
				fmt.Sprintf("state id expected: <lb_id>#<frontend_name>#<backend_name>, got: %v", plan.ID.ValueString()))
			return nil, diags
		}
		lbId, _ := strconv.ParseUint(parameters[0], 10, 64)
		req.LBID = lbId
		fName = parameters[1]
		bName = parameters[2]
	}

	lbItem, err := c.CloudBroker().LB().Get(ctx, req)
	if err != nil {
		diags.AddError(fmt.Sprintf("Cannot get info about lb with ID %v", req.LBID), err.Error())
		return nil, diags
	}

	frontend := &lb.ItemFrontend{}
	frontends := lbItem.Frontends
	for i, f := range frontends {
		if f.Name == fName {
			frontend = &frontends[i]
			break
		}
	}
	if frontend.Name == "" {
		diags.AddError(fmt.Sprintf("can not find frontend with name: %s for lb: %d", fName, lbItem.ID), "")
		return nil, diags
	}

	for _, b := range frontend.Bindings {
		if b.Name == bName {
			return &b, nil
		}
	}

	diags.AddError(fmt.Sprintf("can not find bind with name: %s for frontend: %s for lb: %d", bName, fName, lbItem.ID), "")
	return nil, diags
}

func UpdateLBFrontendBind(ctx context.Context, plan, state *models.ResourceLBFrontendBindModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, fmt.Sprintf("UpdateLBFrontendBind: Start edit lb frontend bind with ID - %v", state.ID.ValueString()))

	diags := diag.Diagnostics{}

	req := lb.FrontendBindUpdateRequest{
		LBID:           uint64(plan.LBID.ValueInt64()),
		FrontendName:   plan.Frontend.ValueString(),
		BindingName:    plan.Name.ValueString(),
		BindingAddress: plan.Address.ValueString(),
		BindingPort:    uint64(plan.Port.ValueInt64()),
	}

	_, err := c.CloudBroker().LB().FrontendBindUpdate(ctx, req)
	if err != nil {
		diags.AddError("UpdateLBFrontendBind: cannot edit lb frontend bind", err.Error())
		return diags
	}

	tflog.Info(ctx, fmt.Sprintf("UpdateLBFrontendBind: Finish edit lb frontend bind with name - %v", req.BindingName))

	return nil
}
