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

func AuditLinkedJobsDataSource(ctx context.Context, state *models.DataSourceAuditLinkedJobs, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start flattens.AuditLinkedJobsDataSource")

	diags := diag.Diagnostics{}

	auditGuid := state.AuditGuid.ValueString()

	recordAudit, diags := utilities.AuditLinkedJobsDataSourceCheckPresence(ctx, auditGuid, c)
	if diags.HasError() {
		return diags
	}

	tflog.Info(ctx, "flattens.AuditLinkedJobsDataSource: before flatten", map[string]any{"audit_guid": auditGuid})

	*state = models.DataSourceAuditLinkedJobs{
		AuditGuid: state.AuditGuid,
		Timeouts:  state.Timeouts,

		ID:    types.StringValue(uuid.New().String()),
		Items: flattenLinkedJobs(ctx, *recordAudit),
	}

	tflog.Info(ctx, "End flattens.AuditLinkedJobsDataSource", map[string]any{"audit_guid": auditGuid})
	return nil
}

func flattenLinkedJobs(ctx context.Context, linkedJobs []audit.ItemLinkedJobs) []models.LinkedJob {
	tflog.Info(ctx, "Start flattenLinkedJobs")

	res := make([]models.LinkedJob, 0, len(linkedJobs))

	for _, item := range linkedJobs {
		temp := models.LinkedJob{
			CMD:        types.StringValue(item.CMD),
			GUID:       types.StringValue(item.GUID),
			NID:        types.Int64Value(int64(item.NID)),
			State:      types.StringValue(item.State),
			TimeCreate: types.Int64Value(int64(item.TimeCreate)),
			TimeStart:  types.Int64Value(int64(item.TimeStart)),
			TimeStop:   types.Int64Value(int64(item.TimeStop)),
			Timeout:    types.Int64Value(int64(item.Timeout)),
		}

		res = append(res, temp)
	}

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