package billing

import (
	"context"

	"apps/backend/internal/middleware"
	billingModule "apps/backend/internal/module/billing"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *CreateBillingCheckoutSessionLogic) CreateBillingCheckoutSession(req *types.BillingCheckoutCreateReq) (resp *types.BillingCheckoutData, err error) {
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, billingModule.ErrInvalidRequest
	}
	a, err := l.svcCtx.Billing.CreateCheckout(l.ctx, uid, req.PlanId, req.RequestId)
	if err != nil {
		return nil, err
	}
	return checkoutData(a), nil
}

func checkoutData(a *billingModule.CheckoutAttempt) *types.BillingCheckoutData {
	return &types.BillingCheckoutData{Id: a.ID, SessionId: a.SessionID, Url: a.URL, ExpiresAt: a.ExpiresAt, Status: a.Status, PaymentStatus: a.PaymentStatus, FulfillmentStatus: a.FulfillmentStatus, PlanId: a.PlanID}
}
