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 CreateResourceLBFrontend(ctx context.Context, plan *models.ResourceLBFrontendModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, fmt.Sprintf("Start create ResourceLBFrontend: frontend_name %s", plan.Name.ValueString()))

	diags := diag.Diagnostics{}

	createReq := lb.FrontendCreateRequest{
		LBID:         uint64(plan.LBID.ValueInt64()),
		BackendName:  plan.Backend.ValueString(),
		FrontendName: plan.Name.ValueString(),
	}

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

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

	return nil
}

func LBFrontendResourceCheckPresence(ctx context.Context, plan *models.ResourceLBFrontendModel, c *client.Client) (*lb.ItemFrontend, diag.Diagnostics) {
	tflog.Info(ctx, fmt.Sprintf("LBFrontendCheckPresence: Get info about LB Frontend with ID - %v", plan.ID.ValueString()))

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

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

	lb, 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
	}

	frontends := lb.Frontends
	for _, f := range frontends {
		if f.Name == fName {
			return &f, diags
		}
	}

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