package bservice

import (
	"context"
	"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/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/bservice/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/ic"
)

// resourceBServiceGroupInputCheck checks if input parameters are valid.
func resourceBServiceGroupInputCheck(ctx context.Context, plan *models.ResourceRecordGroupModel, c *client.Client) diag.Diagnostics {
	diags := diag.Diagnostics{}

	serviceID := uint64(plan.ServiceID.ValueInt64())
	serviceIDValid := true
	tflog.Info(ctx, "resourceBServiceGroupInputCheck: exist resource bservice", map[string]any{"service_id": serviceID})
	err := ic.ExistBservise(ctx, serviceID, c)
	if err != nil {
		serviceIDValid = false
		diags.AddError(fmt.Sprintf("Cannot get info about bservice with ID %v", serviceID), err.Error())
	}

	imageID := uint64(plan.ImageID.ValueInt64())
	tflog.Info(ctx, "resourceBServiceGroupInputCheck: exist resource image", map[string]any{"image_id": imageID})
	err = ic.ExistImage(ctx, imageID, c)
	if err != nil {
		diags.AddError(fmt.Sprintf("Cannot get info about image with ID %v", imageID), err.Error())
	}

	if !plan.ExtNets.IsNull() {
		extnetList := plan.ExtNets.Elements()
		for _, elem := range extnetList {
			extNetID := elem.(types.Int64).ValueInt64()
			err = ic.ExistExtNet(ctx, uint64(extNetID), c)
			if err != nil {
				diags.AddError(fmt.Sprintf("Cannot get info about extnet with ID %v", extNetID), err.Error())
			}
		}
	}

	if !plan.VINSes.IsNull() {
		vinsList := plan.VINSes.Elements()
		for _, elem := range vinsList {
			vinsID := elem.(types.Int64).ValueInt64()
			err = ic.ExistVins(ctx, uint64(vinsID), c)
			if err != nil {
				diags.AddError(fmt.Sprintf("Cannot get info about VINS with ID %v", vinsList), err.Error())
			}
		}
	}

	if serviceIDValid && !plan.Parents.IsNull() {
		parentsList := plan.Parents.Elements()
		for _, elem := range parentsList {
			parentID := elem.(types.Int64).ValueInt64()
			err = ic.ExistBserviseGroup(ctx, serviceID, uint64(parentID), c)
			if err != nil {
				diags.AddError(fmt.Sprintf("Cannot get info about parent group with ID %v", parentID), err.Error())
			}
		}
	}

	return diags
}
