package flattens

import (
	"context"

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

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

	diags := diag.Diagnostics{}

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

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

	*state = models.DataSourceAccountVinsListModel{
		AccountID: state.AccountID,
		VinsID:    state.VinsID,
		Name:      state.Name,
		RGID:      state.RGID,
		ExtIp:     state.ExtIp,
		SortBy:    state.SortBy,
		Page:      state.Page,
		Size:      state.Size,
		Timeouts:  state.Timeouts,

		EntryCount: types.Int64Value(int64(accountVinsList.EntryCount)),
	}
	items := make([]models.ItemVINSModel, 0, len(accountVinsList.Data))
	for _, item := range accountVinsList.Data {
		i := models.ItemVINSModel{
			AccountID:   types.Int64Value(int64(item.ID)),
			AccountName: types.StringValue(item.Name),
			Computes:    types.Int64Value(int64(item.Computes)),
			CreatedBy:   types.StringValue(item.CreatedBy),
			CreatedTime: types.Int64Value(int64(item.CreatedTime)),
			DeletedBy:   types.StringValue(item.DeletedBy),
			DeletedTime: types.Int64Value(int64(item.DeletedTime)),
			ExternalIP:  types.StringValue(item.ExternalIP),
			ExtnetId:    types.Int64Value(int64(item.ExtnetId)),
			FreeIPs:     types.Int64Value(int64(item.FreeIPs)),
			ID:          types.Int64Value(int64(item.ID)),
			Name:        types.StringValue(item.Name),
			Network:     types.StringValue(item.Network),
			PriVNFDevID: types.Int64Value(int64(item.PriVNFDevID)),
			RGID:        types.Int64Value(int64(item.RGID)),
			RGName:      types.StringValue(item.RGName),
			Status:      types.StringValue(item.Status),
			UpdatedBy:   types.StringValue(item.UpdatedBy),
			UpdatedTime: types.Int64Value(int64(item.UpdatedTime)),
		}

		items = append(items, i)
	}

	state.Data = items

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

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