package flattens

import (
	"context"
	"fmt"

	"github.com/google/uuid"
	"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/k8s"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/utilities"
)

func DataSourceK8sComputes(ctx context.Context, state *models.K8SComputesModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start FlattenDataSourceK8sComputes", map[string]any{"k8s_id": state.K8SID.ValueInt64()})

	diags := diag.Diagnostics{}

	k8SID := uint64(state.K8SID.ValueInt64())

	cluster, err := utilities.K8SCPResourceCheckPresence(ctx, k8SID, c)
	if err != nil {
		diags.AddError(fmt.Sprintf("Cannot get info about cluster with ID %d", k8SID), err.Error())
		return diags
	}

	id := uuid.New()

	*state = models.K8SComputesModel{
		K8SID:    state.K8SID,
		Timeouts: state.Timeouts,
		Id:       types.StringValue(id.String()),
		Masters:  flattenMasterComputes(ctx, cluster),
		Workers:  flattenWorkerComputes(ctx, cluster),
	}

	tflog.Info(ctx, "End FlattenDataSourceK8sComputes", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
	return nil
}

func flattenMasterComputes(ctx context.Context, cluster *k8s.RecordK8S) []models.ItemComputeModel {
	tflog.Info(ctx, "Start flattenMasterComputes")

	res := make([]models.ItemComputeModel, 0, len(cluster.K8SGroups.Masters.DetailedInfo))
	for _, detailedInfo := range cluster.K8SGroups.Masters.DetailedInfo {
		temp := models.ItemComputeModel{
			ComputeId:  types.Int64Value(int64(detailedInfo.ID)),
			Name:       types.StringValue(detailedInfo.Name),
			GroupName:  types.StringValue(cluster.K8SGroups.Masters.Name),
			Status:     types.StringValue(detailedInfo.Status),
			TechStatus: types.StringValue(detailedInfo.TechStatus),
		}
		res = append(res, temp)
	}

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

func flattenWorkerComputes(ctx context.Context, cluster *k8s.RecordK8S) []models.ItemComputeModel {
	tflog.Info(ctx, "Start flattenWorkerComputes")

	res := make([]models.ItemComputeModel, 0, len(cluster.K8SGroups.Workers))
	for _, worker := range cluster.K8SGroups.Workers {
		for _, comp := range worker.DetailedInfo {
			temp := models.ItemComputeModel{
				ComputeId:  types.Int64Value(int64(comp.ID)),
				Name:       types.StringValue(comp.Name),
				GroupName:  types.StringValue(worker.Name),
				Status:     types.StringValue(comp.Status),
				TechStatus: types.StringValue(comp.TechStatus),
			}
			res = append(res, temp)
		}
	}
	tflog.Info(ctx, "End flattenWorkerComputes")
	return res
}
