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

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

	diags := diag.Diagnostics{}

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

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

	id := uuid.New()
	*state = models.DataSourceVINSListModel{
		ByID:           state.ByID,
		Name:           state.Name,
		AccountID:      state.AccountID,
		RGID:           state.RGID,
		ExtIP:          state.ExtIP,
		IncludeDeleted: state.IncludeDeleted,
		SortBy:         state.SortBy,
		Page:           state.Page,
		Size:           state.Size,
		Timeouts:       state.Timeouts,

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

	items := make([]models.ItemVinsModel, 0, len(vinsList.Data))
	for _, item := range vinsList.Data {
		v := models.ItemVinsModel{
			AccountID:   types.Int64Value(int64(item.AccountID)),
			AccountName: types.StringValue(item.AccountName),
			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),
			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)),
			VXLANID:     types.Int64Value(int64(item.VXLANID)),
		}
		items = append(items, v)
	}
	state.Items = items

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