package usage

import (
	"context"

	"apps/backend/internal/middleware"
	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type PurchasePlanLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPurchasePlanLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PurchasePlanLogic {
	return &PurchasePlanLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}

func (l *PurchasePlanLogic) PurchasePlan(req *types.UsagePurchaseReq) (*types.UsagePurchasePublic, error) {
	if l.svcCtx.Usage == nil {
		return nil, response.Biz(503, 503001, "usage not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	p, err := l.svcCtx.Usage.PurchasePlan(l.ctx, uid, req.PlanId, req.MockRef)
	if err != nil {
		return nil, err
	}
	// growth-loop: first paid plan → invite reward (single-level)
	if l.svcCtx.Growth != nil {
		if m, merr := l.svcCtx.Members.FindByUID(l.ctx, uid); merr == nil && m != nil && m.ParentUID != nil && *m.ParentUID > 0 {
			parentUID := *m.ParentUID
			inviterPlan := "free"
			if prefs, perr := l.svcCtx.Usage.GetPrefs(l.ctx, parentUID); perr == nil && prefs != nil {
				inviterPlan = prefs.PlanID
			}
			l.svcCtx.Growth.PlanQuota = func(id string) int {
				if id == "@inviter" {
					switch inviterPlan {
					case "starter":
						return 600
					case "pro":
						return 2000
					default:
						return 120
					}
				}
				switch id {
				case "starter":
					return 600
				case "pro":
					return 2000
				default:
					return 120
				}
			}
			_, _ = l.svcCtx.Growth.OnFirstPaidPlan(l.ctx, uid, parentUID, p.PlanID)
		}
	}
	return &types.UsagePurchasePublic{Id: p.ID, PlanId: p.PlanID, MockRef: p.MockRef, CreatedAt: p.CreatedAt}, nil
}
