package flattens

import (
	"context"
	"fmt"
	"strings"

	"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 DataSourceK8sListDeleted(ctx context.Context, state *models.K8SListDeletedModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start FlattenDataSourceK8sListDeleted")

	diags := diag.Diagnostics{}

	k8sList, err := utilities.K8sListDeletedCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Error get k8s list info", err.Error())
		return diags
	}

	id := uuid.New()

	*state = models.K8SListDeletedModel{
		ByID:           state.ByID,
		Name:           state.Name,
		IPAddress:      state.IPAddress,
		RGID:           state.RGID,
		LBID:           state.LBID,
		BasicServiceID: state.BasicServiceID,
		TechStatus:     state.TechStatus,
		SortBy:         state.SortBy,
		Page:           state.Page,
		Size:           state.Size,
		Timeouts:       state.Timeouts,
		Id:             types.StringValue(id.String()),
		Items:          flattenItemsDeleted(ctx, k8sList),
		EntryCount:     types.Int64Value(int64(k8sList.EntryCount)),
	}

	tflog.Info(ctx, "End FlattenDataSourceK8sListDeleted")
	return nil
}

func flattenItemsDeleted(ctx context.Context, data *k8s.ListK8SClusters) []models.ItemInListDeletedK8SModel {
	tflog.Info(ctx, "Start flattenItems")
	var diags diag.Diagnostics

	res := make([]models.ItemInListDeletedK8SModel, 0, len(data.Data))
	for _, item := range data.Data {
		temp := models.ItemInListDeletedK8SModel{
			AccountID:     types.Int64Value(int64(item.AccountID)),
			AccountName:   types.StringValue(item.AccountName),
			BServiceID:    types.Int64Value(int64(item.BServiceID)),
			CIID:          types.Int64Value(int64(item.CIID)),
			CreatedBy:     types.StringValue(item.CreatedBy),
			CreatedTime:   types.Int64Value(int64(item.CreatedTime)),
			DeletedBy:     types.StringValue(item.DeletedBy),
			DeletedTime:   types.Int64Value(int64(item.DeletedTime)),
			Description:   types.StringValue(item.Description),
			ExtNetID:      types.Int64Value(int64(item.ExtNetID)),
			GID:           types.Int64Value(int64(item.GID)),
			GUID:          types.Int64Value(int64(item.GUID)),
			K8SID:         types.Int64Value(int64(item.ID)),
			LBID:          types.Int64Value(int64(item.LBID)),
			Milestones:    types.Int64Value(int64(item.Milestones)),
			Name:          types.StringValue(item.Name),
			NetworkPlugin: types.StringValue(item.NetworkPlugin),
			RGID:          types.Int64Value(int64(item.RGID)),
			RGName:        types.StringValue(item.RGName),
			ServiceAccount: &models.ServiceAccountInListDeletedModel{
				GUID:     types.StringValue(item.ServiceAccount.GUID),
				Password: types.StringValue(item.ServiceAccount.Password),
				Username: types.StringValue(item.ServiceAccount.Username),
			},
			Status:       types.StringValue(item.Status),
			TechStatus:   types.StringValue(item.TechStatus),
			UpdatedBy:    types.StringValue(item.UpdatedBy),
			UpdatedTime:  types.Int64Value(int64(item.UpdatedTime)),
			VINSID:       types.Int64Value(int64(item.VINSID)),
			WorkersGroup: flattenWGDeleted(ctx, &item.WorkersGroup),
		}
		temp.ACL, diags = types.ListValueFrom(ctx, types.StringType, item.ACL)
		if diags != nil {
			tflog.Error(ctx, fmt.Sprint("Error flattenACL", diags))
		}
		res = append(res, temp)
	}

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

func flattenWGDeleted(ctx context.Context, WG *k8s.ListK8SGroups) []models.ItemWGInListDeletedModel {
	tflog.Info(ctx, "Start flattenWG")

	res := make([]models.ItemWGInListDeletedModel, 0, len(*WG))
	var diags diag.Diagnostics
	for _, k8sGroup := range *WG {
		labels := make([]string, 0)
		for _, label := range k8sGroup.Labels {
			if strings.HasPrefix(label, "workersGroupName") {
				continue
			}
			labels = append(labels, label)
		}
		temp := models.ItemWGInListDeletedModel{
			CPU:             types.Int64Value(int64(k8sGroup.CPU)),
			DetailedInfo:    flattenDetailedInfoListDeleted(ctx, &k8sGroup.DetailedInfo),
			Disk:            types.Int64Value(int64(k8sGroup.Disk)),
			GUID:            types.StringValue(k8sGroup.GUID),
			WorkerGroupID:   types.Int64Value(int64(k8sGroup.ID)),
			WorkerGroupName: types.StringValue(k8sGroup.Name),
			Num:             types.Int64Value(int64(k8sGroup.Num)),
			RAM:             types.Int64Value(int64(k8sGroup.RAM)),
		}
		temp.Annotations, diags = types.ListValueFrom(ctx, types.StringType, k8sGroup.Annotations)
		if diags != nil {
			tflog.Error(ctx, fmt.Sprint("Error flattenAnnotations", diags))
		}
		temp.Labels, diags = types.ListValueFrom(ctx, types.StringType, labels)
		if diags != nil {
			tflog.Error(ctx, fmt.Sprint("Error flattenLabels", diags))
		}
		temp.Taints, diags = types.ListValueFrom(ctx, types.StringType, k8sGroup.Taints)
		if diags != nil {
			tflog.Error(ctx, fmt.Sprint("Error flattenTaints", diags))
		}
		res = append(res, temp)
	}

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

func flattenDetailedInfoListDeleted(ctx context.Context, di *k8s.ListDetailedInfo) []models.ItemDetailedInfoInListDeletedModel {
	tflog.Info(ctx, "Start flattenDetailedInfoList")

	res := make([]models.ItemDetailedInfoInListDeletedModel, 0, len(*di))
	for _, info := range *di {
		temp := models.ItemDetailedInfoInListDeletedModel{
			Externalip: types.StringValue(info.Externalip),
			ID:         types.Int64Value(int64(info.ID)),
			Name:       types.StringValue(info.Name),
			Status:     types.StringValue(info.Status),
			TechStatus: types.StringValue(info.TechStatus),
		}
		res = append(res, temp)
	}

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