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

// AccountListDataSource 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 AccountListDataSource(ctx context.Context, state *models.DataSourceAccountListModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start flattens.AccountListDataSource")

	diags := diag.Diagnostics{}

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

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

	id := uuid.New()
	*state = models.DataSourceAccountListModel{
		ByID:     state.ByID,
		Name:     state.Name,
		ACL:      state.ACL,
		Status:   state.Status,
		Page:     state.Page,
		Size:     state.Size,
		Timeouts: state.Timeouts,
		SortBy:   state.SortBy,

		Id:         types.StringValue(id.String()),
		EntryCount: types.Int64Value(int64(accountList.EntryCount)),
	}
	items := make([]models.ItemAccountListModel, 0, len(accountList.Data))
	for _, item := range accountList.Data {
		i := models.ItemAccountListModel{
			CreatedTime: types.Int64Value(int64(item.CreatedTime)),
			DeletedTime: types.Int64Value(int64(item.DeletedTime)),
			AccountID:   types.Int64Value(int64(item.ID)),
			AccountName: types.StringValue(item.Name),
			Status:      types.StringValue(item.Status),
			UpdatedTime: types.Int64Value(int64(item.UpdatedTime)),
			Desc:        types.StringValue(item.Description),
		}
		i.ComputeFeatures, diags = types.ListValueFrom(ctx, types.StringType, item.ComputeFeatures)
		if diags.HasError() {
			tflog.Error(ctx, fmt.Sprint("flattens.AccountListDataSource: cannot flatten item.ComputeFeatures to i.ComputeFeatures", diags))
		}

		aclList := make([]models.RecordACLModel, 0, len(item.ACL))
		for _, acl := range item.ACL {
			a := models.RecordACLModel{
				Explicit:    types.BoolValue(acl.IsExplicit),
				GUID:        types.StringValue(acl.GUID),
				Right:       types.StringValue(acl.Rights),
				Status:      types.StringValue(acl.Status),
				Type:        types.StringValue(acl.Type),
				UserGroupID: types.StringValue(acl.UgroupID),
			}
			aclList = append(aclList, a)
		}

		i.ACL = aclList
		items = append(items, i)
	}
	state.Items = items

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

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