package flattens

import (
	"context"
	"fmt"

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

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

	diags := diag.Diagnostics{}

	fgID := uint64(state.FlipgroupID.ValueInt64())

	recordFG, diags := utilities.FlipgroupDataSourceCheckPresence(ctx, fgID, c)
	if diags.HasError() {
		return diags
	}

	tflog.Info(ctx, "flattens.FlipgroupDataSource: before flatten", map[string]any{"flipgroup_id": fgID})

	*state = models.DataSourceFLIPGroupModel{
		FlipgroupID: state.FlipgroupID,
		Timeouts:    state.Timeouts,

		AccountID:   types.Int64Value(int64(recordFG.AccountID)),
		AccountName: types.StringValue(recordFG.AccountName),
		ClientType:  types.StringValue(recordFG.ClientType),
		ConnID:      types.Int64Value(int64(recordFG.ConnID)),
		ConnType:    types.StringValue(recordFG.ConnType),
		CreatedBy:   types.StringValue(recordFG.CreatedBy),
		CreatedTime: types.Int64Value(int64(recordFG.CreatedTime)),
		DefaultGW:   types.StringValue(recordFG.DefaultGW),
		DeletedBy:   types.StringValue(recordFG.DeletedBy),
		DeletedTime: types.Int64Value(int64(recordFG.DeletedTime)),
		Description: types.StringValue(recordFG.Description),
		ID:          types.Int64Value(int64(recordFG.ID)),
		GID:         types.Int64Value(int64(recordFG.GID)),
		GUID:        types.Int64Value(int64(recordFG.GUID)),
		IP:          types.StringValue(recordFG.IP),
		Milestones:  types.Int64Value(int64(recordFG.Milestones)),
		Name:        types.StringValue(recordFG.Name),
		NetID:       types.Int64Value(int64(recordFG.NetID)),
		NetType:     types.StringValue(recordFG.NetType),
		Network:     types.StringValue(recordFG.Network),
		RGID:        types.Int64Value(int64(recordFG.RGID)),
		RGName:      types.StringValue(recordFG.RGName),
		Status:      types.StringValue(recordFG.Status),
		UpdatedBy:   types.StringValue(recordFG.UpdatedBy),
		UpdatedTime: types.Int64Value(int64(recordFG.UpdatedTime)),
	}

	state.ClientIDs, diags = types.ListValueFrom(ctx, types.Int64Type, recordFG.ClientIDs)
	if diags.HasError() {
		tflog.Error(ctx, fmt.Sprint("flattens.FlipgroupDataSource: cannot flatten recordFG.ClientIDs to state.ClientIDs", diags))
	}

	tflog.Info(ctx, "End flattens.FlipgroupDataSource", map[string]any{"flipgroup_id": state.ID.ValueInt64()})
	return nil
}
