package handlers import ( "encoding/json" "errors" "fmt" "strings" "time" "Yimaru-Backend/internal/domain" "github.com/gofiber/fiber/v2" ) const checkoutLinkRateLimitWindow = 15 * time.Minute type requestCheckoutLinkReq struct { PlanID *int64 `json:"plan_id"` Category *string `json:"category"` } type requestCheckoutLinkRes struct { Channel string `json:"channel"` DestinationHint string `json:"destination_hint"` } // RequestSubscriptionCheckoutLink godoc // @Summary Send web checkout link to learner // @Description Sends the standalone web checkout URL to the learner by email or SMS (registration channel). Intended when mobile clients show a subscription-required state. // @Tags subscriptions // @Accept json // @Produce json // @Param body body requestCheckoutLinkReq false "Optional plan or category for deep link" // @Success 200 {object} domain.Response // @Failure 400 {object} domain.ErrorResponse // @Failure 409 {object} domain.ErrorResponse // @Failure 429 {object} domain.ErrorResponse // @Failure 503 {object} domain.ErrorResponse // @Router /api/v1/subscriptions/request-checkout-link [post] func (h *Handler) RequestSubscriptionCheckoutLink(c *fiber.Ctx) error { userID, ok := c.Locals("user_id").(int64) if !ok { return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{ Message: "Unauthorized", }) } checkoutBase := strings.TrimSpace(h.Cfg.LearnerWebCheckoutBaseURL) if checkoutBase == "" { return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{ Message: "Web checkout is not configured", Error: "LEARNER_WEB_CHECKOUT_BASE_URL is not set", }) } if err := h.enforceCheckoutLinkRateLimit(c, userID); err != nil { return c.Status(fiber.StatusTooManyRequests).JSON(domain.ErrorResponse{ Message: "Checkout link was sent recently. Please check your messages or try again later.", Error: err.Error(), }) } var req requestCheckoutLinkReq if len(c.Body()) > 0 { if err := c.BodyParser(&req); err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid request body", Error: err.Error(), }) } } var planCategory string if req.PlanID != nil && *req.PlanID > 0 { plan, err := h.subscriptionsSvc.GetPlanByID(c.Context(), *req.PlanID) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid subscription plan", Error: err.Error(), }) } if !plan.IsActive { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Subscription plan is not available", }) } planCategory = plan.Category } else if req.Category != nil { cat := strings.ToUpper(strings.TrimSpace(*req.Category)) if cat != "" && !domain.IsValidSubscriptionCategory(cat) { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid category", Error: "category must be one of: LEARN_ENGLISH, IELTS, DUOLINGO", }) } planCategory = cat } if planCategory != "" { active, err := h.subscriptionsSvc.HasActiveSubscriptionByCategory( c.Context(), userID, domain.SubscriptionCategory(planCategory), ) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to check subscription status", Error: err.Error(), }) } if active { return c.Status(fiber.StatusConflict).JSON(domain.ErrorResponse{ Message: "You already have an active subscription for this content", }) } } user, err := h.userSvc.GetUserByID(c.Context(), userID) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to load user profile", Error: err.Error(), }) } channel, destination, err := domain.ResolveCheckoutLinkDeliveryChannel(user) if err != nil { if errors.Is(err, domain.ErrNoContactForCheckoutLink) { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "No email or phone number on your account to send a checkout link", Error: err.Error(), }) } return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Cannot send checkout link", Error: err.Error(), }) } checkoutURL := domain.BuildWebCheckoutURL(checkoutBase, req.PlanID, req.Category) if checkoutURL == "" { return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{ Message: "Web checkout is not configured", }) } if err := h.deliverCheckoutLink(c, channel, destination, checkoutURL); err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to send checkout link", Error: err.Error(), }) } meta, _ := json.Marshal(map[string]string{ "channel": string(channel), "checkout_url": checkoutURL, }) h.recordActivity(c, domain.ActionSubscriptionCheckoutLinkSent, domain.ResourceSubscription, req.PlanID, "Sent web checkout link to learner", meta) return c.JSON(domain.Response{ Message: checkoutLinkSentMessage(channel), Data: requestCheckoutLinkRes{ Channel: string(channel), DestinationHint: domain.MaskCheckoutLinkDestination(channel, destination), }, }) } func checkoutLinkSentMessage(channel domain.CheckoutLinkDeliveryChannel) string { switch channel { case domain.CheckoutLinkDeliveryEmail: return "Please check your email for the address" case domain.CheckoutLinkDeliverySMS: return "Please check your SMS for the address" default: return "Please check your email/SMS for the address" } } func (h *Handler) enforceCheckoutLinkRateLimit(c *fiber.Ctx, userID int64) error { since := time.Now().Add(-checkoutLinkRateLimitWindow) action := string(domain.ActionSubscriptionCheckoutLinkSent) filter := domain.ActivityLogFilter{ ActorID: &userID, Action: &action, After: &since, Limit: 1, Offset: 0, } logs, _, err := h.activityLogSvc.List(c.Context(), filter) if err != nil { return err } if len(logs) > 0 { return fmt.Errorf("rate limit: one checkout link per %s", checkoutLinkRateLimitWindow) } return nil } func (h *Handler) deliverCheckoutLink(c *fiber.Ctx, channel domain.CheckoutLinkDeliveryChannel, destination, checkoutURL string) error { subject := "Complete your Yimaru Academy subscription" text := fmt.Sprintf( "Complete your Yimaru Academy subscription here:\n\n%s\n\nAfter payment, open the mobile app and sign in with this account.", checkoutURL, ) html := fmt.Sprintf( `
Complete your Yimaru Academy subscription using the link below:
After payment, open the mobile app and sign in with this account.
`, checkoutURL, ) sms := fmt.Sprintf("Complete your Yimaru Academy subscription: %s", checkoutURL) ctx := c.Context() messenger := h.notificationSvc.MessengerSvc() switch channel { case domain.CheckoutLinkDeliveryEmail: return messenger.SendEmail(ctx, destination, text, html, subject) case domain.CheckoutLinkDeliverySMS: return messenger.SendSMS(ctx, destination, sms) default: return fmt.Errorf("unsupported delivery channel %q", channel) } }