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

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

	diags := diag.Diagnostics{}

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

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

	id := uuid.New()
	*state = models.DataSourceExtNetListModel{
		AccountID: state.AccountID,
		ByID:      state.ByID,
		Name:      state.Name,
		Network:   state.Network,
		VLANID:    state.VLANID,
		VNFDevID:  state.VNFDevID,
		OVSBridge: state.OVSBridge,
		Status:    state.Status,
		Page:      state.Page,
		Size:      state.Size,
		Timeouts:  state.Timeouts,
		SortBy:    state.SortBy,

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

	items := make([]models.ItemExtNetModel, 0, len(extNetList.Data))
	for _, item := range extNetList.Data {
		i := models.ItemExtNetModel{
			ID:     types.Int64Value(int64(item.ID)),
			IPCIDR: types.StringValue(item.IPCIDR),
			Name:   types.StringValue(item.Name),
			Status: types.StringValue(item.Status),
		}
		items = append(items, i)
	}
	state.Items = items

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

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