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/k8ci"

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

	diags := diag.Diagnostics{}

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

	id := uuid.New()

	*state = models.K8ciListModel{
		ByID:            state.ByID,
		Name:            state.Name,
		Status:          state.Status,
		WorkerDriver:    state.WorkerDriver,
		MasterDriver:    state.MasterDriver,
		NetworkPlugins:  state.NetworkPlugins,
		IncludeDisabled: state.IncludeDisabled,
		SortBy:          state.SortBy,
		Page:            state.Page,
		Size:            state.Size,
		Timeouts:        state.Timeouts,
		Id:              types.StringValue(id.String()),
		Items:           flattenK8ciItems(ctx, k8ciList),
		EntryCount:      types.Int64Value(int64(k8ciList.EntryCount)),
	}

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

func flattenK8ciItems(ctx context.Context, data *k8ci.ListK8CI) []models.ItemInListK8ciModel {
	tflog.Info(ctx, "Start flattenK8ciItems")
	var diags diag.Diagnostics

	res := make([]models.ItemInListK8ciModel, 0, len(data.Data))
	for _, item := range data.Data {
		temp := models.ItemInListK8ciModel{
			CreatedTime: types.Int64Value(int64(item.CreatedTime)),
			Description: types.StringValue(item.Description),
			K8CIID:      types.Int64Value(int64(item.ID)),
			LBImageID:   types.Int64Value(int64(item.LBImageID)),
			K8CIName:    types.StringValue(item.Name),
			Status:      types.StringValue(item.Status),
			Version:     types.StringValue(item.Version),
		}
		temp.NetworkPlugins, diags = types.ListValueFrom(ctx, types.StringType, item.NetworkPlugins)
		if diags != nil {
			tflog.Error(ctx, fmt.Sprint("Error flatten NetworkPlugins", diags))
		}
		res = append(res, temp)
	}

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