package records

import (
	"context"
	"fmt"
	"strings"

	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/nexuscrm/shared/pkg/models"
)

// LoadOutboxRecordPayload lets the outbox worker expand a minimal durable
// RecordCreated marker into the committed record image before publishing to
// generic subscribers.
func (ps *PersistenceService) LoadOutboxRecordPayload(ctx context.Context, objectAPIName, recordID string, _ *models.UserSession) (models.SObject, error) {
	if ps == nil || ps.repo == nil {
		return nil, fmt.Errorf("persistence service is not wired")
	}
	objectAPIName = strings.TrimSpace(objectAPIName)
	recordID = strings.TrimSpace(recordID)
	if objectAPIName == "" || recordID == "" {
		return nil, fmt.Errorf("object api name and record id are required")
	}
	readCtx := constants.WithSecurityContext(ps.DetachTx(ctx), constants.SystemContext, "outbox RecordCreated payload rehydrate")
	record, err := ps.repo.FindOne(readCtx, objectAPIName, recordID)
	if err != nil {
		return nil, err
	}
	if record == nil {
		return nil, nil
	}
	if record.GetString(constants.FieldID) == "" {
		record[constants.FieldID] = recordID
	}
	return record, nil
}
