package runtimeworker

import (
	"context"
	"testing"

	"github.com/nexuscrm/automation"
	recordmutation "github.com/nexuscrm/backend/internal/runtimeassembly/recordmutation"
	"github.com/nexuscrm/persistence"
	sharedcontract "github.com/nexuscrm/shared/pkg/contract"
	"github.com/nexuscrm/shared/pkg/models"
	outboundintentv1 "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/outboundintentv1"
)

type runtimeWorkerOutboundMailAttachmentMetadataStub struct{}

func (runtimeWorkerOutboundMailAttachmentMetadataStub) AuthorizeRecordAttachmentMetadata(
	context.Context,
	string,
	*models.UserSession,
) (*sharedcontract.RecordAttachmentMetadata, bool, error) {
	return nil, false, nil
}

type runtimeWorkerOutboundIntentSinkStub struct{}

func (runtimeWorkerOutboundIntentSinkStub) Enqueue(
	context.Context,
	persistence.RuntimeOutboundIntentScope,
	outboundintentv1.Intent,
) (persistence.RuntimeOutboundIntentRow, bool, error) {
	return persistence.RuntimeOutboundIntentRow{}, false, nil
}

func TestBindRuntimeRecordEventOutboundIntentsInstallsAttachmentMetadataBeforeHandlers(t *testing.T) {
	flows := automation.NewFlowExecutor(nil, nil, nil, nil, nil, nil, nil)
	graph := &recordmutation.RecordsMutationRuntime{Flows: flows}
	authorizer := runtimeWorkerOutboundMailAttachmentMetadataStub{}
	if err := bindRuntimeRecordEventOutboundIntents(
		graph,
		authorizer,
		runtimeWorkerOutboundIntentSinkStub{},
	); err != nil {
		t.Fatal(err)
	}
	if got := flows.StandardActionContractDeps().RecordAttachmentMetadata; got != authorizer {
		t.Fatalf("record-event outbound mail attachment metadata authorizer = %#v, want %#v", got, authorizer)
	}
	if err := bindRuntimeRecordEventOutboundIntents(
		graph,
		authorizer,
		runtimeWorkerOutboundIntentSinkStub{},
	); err == nil {
		t.Fatal("record-event worker accepted a second outbound-intent dependency owner")
	}
}
