package flattens

import (
	"context"

	"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/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/flattens"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/k8ci/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/k8ci/utilities"
)

// K8CIListDataSource flattens data source for k8ci list.
// Return error in case data source is not found on the platform.
// Flatten errors are added to tflog.
func K8CIListDataSource(ctx context.Context, state *models.DataSourceK8CIListModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start flattens.K8CIListDataSource")

	diags := diag.Diagnostics{}

	k8ciList, diags := utilities.K8CIListDataSourceCheckPresence(ctx, state, c)
	if diags.HasError() {
		return diags
	}

	tflog.Info(ctx, "flattens.K8CIListDataSource: before flatten")

	id := uuid.New()
	*state = models.DataSourceK8CIListModel{
		ByID:            state.ByID,
		Name:            state.Name,
		Status:          state.Status,
		WorkerDriver:    state.WorkerDriver,
		MasterDriver:    state.MasterDriver,
		NetworkPlugin:   state.NetworkPlugin,
		IncludeDisabled: state.IncludeDisabled,
		SortBy:          state.SortBy,
		Page:            state.Page,
		Size:            state.Size,
		Timeouts:        state.Timeouts,

		Id:         types.StringValue(id.String()),
		EntryCount: types.Int64Value(int64(k8ciList.EntryCount)),
	}

	items := make([]models.ItemK8ciModel, 0, len(k8ciList.Data))
	for _, item := range k8ciList.Data {
		v := models.ItemK8ciModel{
			CreatedTime:    types.Int64Value(int64(item.CreatedTime)),
			Description:    types.StringValue(item.Description),
			GID:            types.Int64Value(int64(item.GID)),
			GUID:           types.Int64Value(int64(item.GUID)),
			K8ciID:         types.Int64Value(int64(item.ID)),
			LBImageID:      types.Int64Value(int64(item.LBImageID)),
			MasterDriver:   types.StringValue(item.MasterDriver),
			MasterImageId:  types.Int64Value(int64(item.MasterImageID)),
			MaxMasterCount: types.Int64Value(int64(item.MaxMasterCount)),
			MaxWorkerCount: types.Int64Value(int64(item.MaxWorkerCount)),
			Name:           types.StringValue(item.Name),
			SharedWith:     flattens.FlattenSimpleTypeToList(ctx, types.Int64Type, &item.SharedWith),
			Status:         types.StringValue(item.Status),
			Version:        types.StringValue(item.Version),
			WorkerDriver:   types.StringValue(item.WorkerDriver),
			WorkerImageId:  types.Int64Value(int64(item.WorkerImageID)),
		}
		items = append(items, v)
	}
	state.Items = items

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