package vipconfig

import (
	"context"
	"fmt"
	"strings"

	activityv1 "hyapp.local/api/proto/activity/v1"
)

const vipGrantNoticeTitle = "System Gift"

func (h *Handler) createVIPGrantNotice(ctx context.Context, requestID string, appCode string, commandID string, targetUserID int64, level int32, transactionID string) error {
	body := fmt.Sprintf("You received VIP%d.", level)
	eventID := strings.TrimSpace(transactionID)
	if eventID == "" {
		eventID = strings.TrimSpace(commandID)
	}
	return h.createVIPSystemNotice(ctx, requestID, appCode, targetUserID, "vip_grant:"+eventID, "AdminVIPGranted", commandID, body)
}

func (h *Handler) createVIPTrialCardGrantNotice(ctx context.Context, requestID string, appCode string, commandID string, targetUserID int64, level int32, trialCardID string) error {
	body := fmt.Sprintf("You received a VIP%d trial card.", level)
	eventID := strings.TrimSpace(trialCardID)
	if eventID == "" {
		eventID = strings.TrimSpace(commandID)
	}
	return h.createVIPSystemNotice(ctx, requestID, appCode, targetUserID, "vip_trial_card_grant:"+eventID, "AdminVIPTrialCardGranted", commandID, body)
}

func (h *Handler) createVIPSystemNotice(ctx context.Context, requestID string, appCode string, targetUserID int64, producerEventID string, producerEventType string, aggregateID string, body string) error {
	if h.activity == nil {
		// Tests and isolated local handlers may omit integrations; the production constructor always wires activity-service.
		return nil
	}
	_, err := h.activity.CreateInboxMessage(ctx, &activityv1.CreateInboxMessageRequest{
		Meta:              &activityv1.RequestMeta{RequestId: strings.TrimSpace(requestID), Caller: "admin-server", AppCode: strings.TrimSpace(appCode)},
		TargetUserId:      targetUserID,
		Producer:          "admin-server",
		ProducerEventId:   strings.TrimSpace(producerEventID),
		ProducerEventType: producerEventType,
		MessageType:       "system",
		AggregateType:     "vip_grant",
		AggregateId:       strings.TrimSpace(aggregateID),
		Title:             vipGrantNoticeTitle,
		Summary:           body,
		Body:              body,
	})
	return err
}
