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

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

	diags := diag.Diagnostics{}

	compsList, err := utilities.ExtNetComputesListCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Cannot get info about extnet list", err.Error())
		return diags
	}

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

	id := uuid.New()
	*state = models.DataSourceExtNetComputesListModel{
		AccountID: state.AccountID,
		RGID:      state.RGID,
		ComputeID: state.ComputeID,
		Page:      state.Page,
		Size:      state.Size,
		Timeouts:  state.Timeouts,
		SortBy:    state.SortBy,

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

	items := make([]models.ItemComputeModel, 0, len(compsList.Data))
	for _, item := range compsList.Data {
		i := models.ItemComputeModel{
			AccountID:   types.Int64Value(int64(item.AccountID)),
			AccountName: types.StringValue(item.AccountName),
			ID:          types.Int64Value(int64(item.ID)),
			Name:        types.StringValue(item.Name),
			RGID:        types.Int64Value(int64(item.RGID)),
			RGName:      types.StringValue(item.RGName),
		}

		extnets := make([]models.ItemComputeExtNetModel, 0, len(item.ExtNets))
		for _, en := range item.ExtNets {
			e := models.ItemComputeExtNetModel{
				NetId:  types.Int64Value(int64(en.ID)),
				IpAddr: types.StringValue(en.IPAddr),
				IPCIDR: types.StringValue(en.IPCIDR),
				Name:   types.StringValue(en.Name),
			}
			extnets = append(extnets, e)
		}
		i.ExtNets = extnets
		items = append(items, i)
	}

	state.Items = items

	tflog.Info(ctx, "flattens.ExtNetComputesListDataSource: after flatten")

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