package order

import (
	"context"
	"encoding/json"
	"time"

	commonLogic "github.com/perfect-panel/server/internal/logic/common"
	"github.com/perfect-panel/server/internal/types"
	"gorm.io/gorm"
)

type newUserDiscountEligibility struct {
	Eligibility         *commonLogic.NewUserEligibilityContext
	Discounts           []types.SubscribeDiscount
	NewUserOnly         bool
	WithinWindow        bool
	EligibleForDiscount bool
}

func resolveNewUserDiscountEligibility(
	ctx context.Context,
	db *gorm.DB,
	currentUserID int64,
	subscribeID int64,
	quantity int64,
	discountJSON string,
) (*newUserDiscountEligibility, error) {
	state := &newUserDiscountEligibility{}
	if discountJSON == "" {
		return state, nil
	}

	_ = json.Unmarshal([]byte(discountJSON), &state.Discounts)
	state.NewUserOnly = isNewUserOnlyForQuantity(state.Discounts, quantity)

	eligibility, err := commonLogic.ResolveNewUserEligibility(ctx, db, currentUserID)
	if err != nil {
		return nil, err
	}
	state.Eligibility = eligibility
	state.WithinWindow = eligibility.IsNewUserAt(time.Now())
	state.EligibleForDiscount = state.WithinWindow

	if state.EligibleForDiscount && state.NewUserOnly {
		historyCount, countErr := commonLogic.CountScopedSubscribePurchaseOrders(
			ctx,
			db,
			eligibility.ScopeUserIDs,
			0,
			[]int64{2, 5},
			"",
		)
		if countErr != nil {
			return nil, countErr
		}
		if historyCount >= 1 {
			state.EligibleForDiscount = false
		}
	}

	return state, nil
}
