package common

import (
	"context"
	"errors"

	"github.com/perfect-panel/server/internal/model/user"
)

type PurchaseRoute string

const (
	PurchaseRouteNewPurchase       PurchaseRoute = "new_purchase"
	PurchaseRoutePurchaseToRenewal PurchaseRoute = "purchase_to_renewal"
)

var (
	ErrSingleModePlanMismatch = errors.New("single subscribe mode plan mismatch")
)

type PurchaseRouteDecision struct {
	SingleMode          bool
	Route               PurchaseRoute
	ResolvedSubscribeID int64
	Anchor              *user.Subscribe
}

type FindSingleModeAnchorFunc func(ctx context.Context, userID int64) (*user.Subscribe, error)

func ResolvePurchaseRoute(
	ctx context.Context,
	singleMode bool,
	userID int64,
	requestedSubscribeID int64,
	findAnchor FindSingleModeAnchorFunc,
) (*PurchaseRouteDecision, error) {
	decision := &PurchaseRouteDecision{
		SingleMode:          singleMode,
		Route:               PurchaseRouteNewPurchase,
		ResolvedSubscribeID: requestedSubscribeID,
	}

	if !singleMode || userID == 0 || findAnchor == nil {
		return decision, nil
	}

	anchorSub, err := findAnchor(ctx, userID)
	if err != nil {
		return nil, err
	}
	if anchorSub == nil {
		return decision, nil
	}

	decision.Route = PurchaseRoutePurchaseToRenewal
	decision.ResolvedSubscribeID = requestedSubscribeID
	decision.Anchor = anchorSub
	return decision, nil
}
