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/decort-golang-sdk/pkg/cloudapi/compute"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/kvmvm/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/kvmvm/utilities"
)

func DataSourceComputeUserList(ctx context.Context, state *models.ListUsersModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start FlattenDataSourceComputeUserList")

	diags := diag.Diagnostics{}

	userList, err := utilities.ComputeUserListCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Error get compute user list info", err.Error())
		return diags
	}

	id := uuid.New()

	*state = models.ListUsersModel{
		ComputeID:  state.ComputeID,
		Timeouts:   state.Timeouts,
		Id:         types.StringValue(id.String()),
		Items:      flattenUserList(ctx, userList),
		EntryCount: types.Int64Value(int64(userList.EntryCount)),
	}

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

func flattenUserList(ctx context.Context, users *compute.ListUsers) *models.RecordACLInListUsersModel {
	tflog.Info(ctx, "Start flattenUserList")

	res := models.RecordACLInListUsersModel{
		AccountACL: flattenACLInUserList(ctx, &users.Data.AccountACL),
		ComputeACL: flattenACLInUserList(ctx, &users.Data.ComputeACL),
		RGACL:      flattenACLInUserList(ctx, &users.Data.RGACL),
	}

	tflog.Info(ctx, "End flattenUserList")
	return &res
}

func flattenACLInUserList(ctx context.Context, acl *compute.ListACL) []models.ItemACLInListUsersModel {
	tflog.Info(ctx, "Start flattenACLInUserList")

	res := make([]models.ItemACLInListUsersModel, 0, len(*acl))
	for _, item := range *acl {
		temp := models.ItemACLInListUsersModel{
			Explicit:    types.BoolValue(bool(item.Explicit)),
			GUID:        types.StringValue(item.GUID),
			Right:       types.StringValue(item.Right),
			Status:      types.StringValue(item.Status),
			Type:        types.StringValue(item.Type),
			UserGroupID: types.StringValue(item.UserGroupID),
		}
		res = append(res, temp)
	}

	tflog.Info(ctx, "End flattenACLInUserList")
	return res
}
