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

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

	diags := diag.Diagnostics{}

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

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

	id := uuid.New()
	*state = models.DataSourceDiskListTypesDetailedModel{
		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)),
	}

	items := make([]models.ItemDiskTypeDetailedModel, 0, len(listTypes.Data))
	for _, typeListDetailed := range listTypes.Data {
		typeMap := typeListDetailed.(map[string]interface{})

		t := models.ItemDiskTypeDetailedModel{
			SepID:   types.Int64Value(int64(typeMap["sepId"].(float64))),
			SepName: types.StringValue(typeMap["sepName"].(string)),
		}

		var pools []models.ItemPoolModel
		poolsTemp := typeMap["pools"].([]interface{})
		for _, pool := range poolsTemp {
			poolsMap := pool.(map[string]interface{})
			p := models.ItemPoolModel{
				Name:   types.StringValue(poolsMap["name"].(string)),
				System: types.StringValue(poolsMap["system"].(string)),
			}

			p.Types, diags = types.ListValueFrom(ctx, types.StringType, flattenTypes(poolsMap["types"].([]interface{})))
			if diags != nil {
				tflog.Error(ctx, fmt.Sprint("flattens.DiskListTypesDetailedDataSource: cannot flatten poolsMap[\"types\"] to p.Types", diags))
			}
			pools = append(pools, p)
		}
		t.Pools = pools
		items = append(items, t)
	}
	state.Items = items

	tflog.Info(ctx, "flattens.DiskListTypesDetailedDataSource: end flatten")
	return diags
}

func flattenTypes(typesInterface []interface{}) []string {
	var typesList []string
	for _, typ := range typesInterface {
		typesList = append(typesList, typ.(string))
	}
	return typesList
}
