package threading

import (
	"context"

	"github.com/jackc/pgx/v5/pgxpool"
)

// ApplyMessageThread assigns thread_id for one message and propagates to direct replies.
func ApplyMessageThread(
	ctx context.Context,
	db *pgxpool.Pool,
	accountID, rowID, rfcMessageID, inReplyTo string,
	references []string,
) error {
	threadID, err := AssignThreadID(ctx, db, accountID, inReplyTo, references)
	if err != nil {
		return err
	}
	if _, err := db.Exec(ctx, `
		UPDATE messages SET thread_id = $1::uuid, updated_at = NOW() WHERE id = $2
	`, threadID, rowID); err != nil {
		return err
	}
	return propagateThreadToReplies(ctx, db, accountID, threadID, rfcMessageID)
}

func propagateThreadToReplies(ctx context.Context, db *pgxpool.Pool, accountID, threadID, rfcMessageID string) error {
	rfcMessageID = NormalizeMessageID(rfcMessageID)
	if rfcMessageID == "" {
		return nil
	}
	_, err := db.Exec(ctx, `
		UPDATE messages
		SET thread_id = $1::uuid, updated_at = NOW()
		WHERE account_id = $2
		  AND thread_id IS DISTINCT FROM $1::uuid
		  AND (
		    in_reply_to = $3
		    OR $3 = ANY(references_header)
		  )
	`, threadID, accountID, rfcMessageID)
	return err
}
