package app

import (
	"context"
	"fmt"
	"strings"

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

// GetAppNotificationCardForUser returns the current interactive-card
// projection after applying the same message-owned visibility authority used
// by actions and other message sidecars.
func (store *Store) GetAppNotificationCardForUser(ctx context.Context, userID, workspaceID, messageID string) (AppNotificationCardView, error) {
	if store == nil || store.db == nil {
		return AppNotificationCardView{}, fmt.Errorf("App notification store is not configured")
	}
	userID = strings.TrimSpace(userID)
	workspaceID = strings.TrimSpace(workspaceID)
	messageID = strings.TrimSpace(messageID)
	if userID == "" || workspaceID == "" || messageID == "" {
		return AppNotificationCardView{}, badRequest("userId, workspaceId, and messageId are required")
	}

	var view AppNotificationCardView
	if err := coredb.WithTx(ctx, store.db, func(tx coredb.Tx) error {
		if err := store.authorizeMessageSidecarReadForUser(
			ctx,
			tx,
			userID,
			workspaceID,
			messageID,
			message.SidecarKindAppNotificationCard,
		); err != nil {
			return err
		}
		card, err := store.LoadAppNotificationCardInTx(ctx, tx, messageID, false)
		if err != nil {
			return err
		}
		notification, err := store.LoadAppNotificationInTx(ctx, tx, workspaceID, card.AppNotificationID, false)
		if err != nil {
			return err
		}
		if notification.MessageID != card.MessageID || notification.ScopeID != card.ScopeID {
			return conflict("App notification card does not match its notification")
		}
		view = AppNotificationCardView{
			NotificationID:       notification.ID,
			NotificationRevision: notification.Revision,
			NotificationStatus:   notification.Status,
			MessageID:            card.MessageID,
			ScopeID:              card.ScopeID,
			SchemaVersion:        card.SchemaVersion,
			CardRevision:         card.CardRevision,
			RenderPayloadJSON:    append([]byte(nil), card.RenderPayloadJSON...),
			State:                card.State,
			ExpiresAt:            card.ExpiresAt,
			CreatedAt:            card.CreatedAt,
			UpdatedAt:            card.UpdatedAt,
		}
		return nil
	}); err != nil {
		return AppNotificationCardView{}, err
	}
	return view, nil
}
