package tenant

import (
	"time"

	"quyun/v2/app/http/tenant/dto"
	"quyun/v2/app/services"
	"quyun/v2/database/models"

	"github.com/gofiber/fiber/v3"
	log "github.com/sirupsen/logrus"
)

// order provides tenant-side order endpoints for members (purchase and my orders).
//
//	@provider
type order struct{}

// purchaseContent
//
//	@Summary	购买内容（余额支付）
//	@Tags		Tenant
//	@Accept		json
//	@Produce	json
//	@Param		tenantCode	path		string					true	"Tenant Code"
//	@Param		contentID	path		int64					true	"ContentID"
//	@Param		form		body		dto.PurchaseContentForm	true	"Form"
//	@Success	200			{object}	dto.PurchaseContentResponse
//
//	@Router		/t/:tenantCode/v1/contents/:contentID/purchase [post]
//	@Bind		tenant local key(tenant)
//	@Bind		user local key(user)
//	@Bind		contentID path
//	@Bind		form body
func (*order) purchaseContent(ctx fiber.Ctx, tenant *models.Tenant, user *models.User, contentID int64, form *dto.PurchaseContentForm) (*dto.PurchaseContentResponse, error) {
	log.WithFields(log.Fields{
		"tenant_id":       tenant.ID,
		"user_id":         user.ID,
		"content_id":      contentID,
		"idempotency_key": form.IdempotencyKey,
	}).Info("tenant.order.purchase_content")

	res, err := services.Order.PurchaseContent(ctx, &services.PurchaseContentParams{
		TenantID:       tenant.ID,
		UserID:         user.ID,
		ContentID:      contentID,
		IdempotencyKey: form.IdempotencyKey,
		Now:            time.Now(),
	})
	if err != nil {
		return nil, err
	}

	return &dto.PurchaseContentResponse{
		Order:      res.Order,
		Item:       res.OrderItem,
		Access:     res.Access,
		AmountPaid: res.AmountPaid,
	}, nil
}
