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

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

	diags := diag.Diagnostics{}

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

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

	id := uuid.New()
	*state = models.DataSourceDiskListTypesModel{
		SortBy:   state.SortBy,
		Page:     state.Page,
		Size:     state.Size,
		Timeouts: state.Timeouts,

		// computed fields
		Id:         types.StringValue(id.String()),
		EntryCount: types.Int64Value(int64(listTypes.EntryCount)),
	}

	state.Types, diags = types.ListValueFrom(ctx, types.StringType, listTypes.Data)
	if diags != nil {
		tflog.Error(ctx, fmt.Sprint("flattens.DiskListTypesDataSource: cannot flatten listTypes.Data to state.Types", diags))
	}

	tflog.Info(ctx, "flattens.DiskListTypesDataSource: end flatten")
	return nil
}
