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"
)

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

	diags := diag.Diagnostics{}

	k8ciID := uint64(state.K8ciID.ValueInt64())

	recordK8ci, diags := utilities.K8ciDataSourceCheckPresence(ctx, k8ciID, c)
	if diags.HasError() {
		return diags
	}

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

	id := uuid.New()
	*state = models.DataSourceK8CIModel{
		K8ciID:   state.K8ciID,
		Timeouts: state.Timeouts,

		Description:    types.StringValue(recordK8ci.Description),
		GID:            types.Int64Value(int64(recordK8ci.GID)),
		GUID:           types.Int64Value(int64(recordK8ci.GUID)),
		Id:             types.StringValue(id.String()),
		LBImageID:      types.Int64Value(int64(recordK8ci.LBImageID)),
		MasterDriver:   types.StringValue(recordK8ci.MasterDriver),
		MasterImageId:  types.Int64Value(int64(recordK8ci.MasterImageID)),
		MaxMasterCount: types.Int64Value(int64(recordK8ci.MaxMasterCount)),
		MaxWorkerCount: types.Int64Value(int64(recordK8ci.MaxWorkerCount)),
		Milestones:     types.Int64Value(int64(recordK8ci.Milestones)),
		Name:           types.StringValue(recordK8ci.Name),
		NetworkPlugins: flattens.FlattenSimpleTypeToList(ctx, types.StringType, &recordK8ci.NetworkPlugins),
		SharedWith:     flattens.FlattenSimpleTypeToList(ctx, types.Int64Type, &recordK8ci.SharedWith),
		Status:         types.StringValue(recordK8ci.Status),
		Version:        types.StringValue(recordK8ci.Version),
		WorkerDriver:   types.StringValue(recordK8ci.WorkerDriver),
		WorkerImageId:  types.Int64Value(int64(recordK8ci.WorkerImageID)),
	}

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