package app

import (
	"context"
	"fmt"
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/coredb"
	"github.com/tidbcloud/AgentTeam/internal/store/message"
	"github.com/tidbcloud/AgentTeam/internal/store/model"
)

// AppendKnowledgeAssistantMessageTx is the transaction-aware form used by the
// hosted Q&A finalizer so the formal answer and its terminal turn state commit
// together. Callers own the transaction and post-commit delivery lifecycle.
func (store *Store) AppendKnowledgeAssistantMessageTx(
	ctx context.Context,
	tx coredb.Tx,
	ownerUserID string,
	workspaceID string,
	threadChannelID string,
	installation model.RuntimeAppInstallation,
	content string,
	metadata map[string]any,
	clientMessageID string,
) (message.MessageDelivery, error) {
	if store == nil || store.db == nil || tx == nil {
		return message.MessageDelivery{}, fmt.Errorf("app store is not configured")
	}
	ownerUserID = strings.TrimSpace(ownerUserID)
	workspaceID = strings.TrimSpace(workspaceID)
	threadChannelID = strings.TrimSpace(threadChannelID)
	if ownerUserID == "" || workspaceID == "" || threadChannelID == "" {
		return message.MessageDelivery{}, badRequest("owner, workspace, and reply thread are required")
	}
	membership, target, err := store.resolveAuthorizedHumanMessageTargetWithQueryer(
		ctx,
		tx,
		ownerUserID,
		workspaceID,
		threadChannelID,
		channelPostAction,
		dmPostAction,
		threadPostAction,
	)
	if err != nil {
		return message.MessageDelivery{}, err
	}
	delivery, _, err := store.appendAppServiceMessageWithOptions(
		ctx,
		tx,
		installation,
		target,
		content,
		metadata,
		true,
		appendMessageOptions{
			ClientMessageID:            strings.TrimSpace(clientMessageID),
			SuppressAgentRouting:       true,
			NotifyPrincipalMemberID:    strings.TrimSpace(membership.Member.ID),
			IdempotencySubjectMemberID: strings.TrimSpace(membership.Member.ID),
		},
		appServiceMessageKnowledgeQA,
		nil,
	)
	return delivery, err
}
