package common

import (
	"context"

	"github.com/perfect-panel/server/internal/model/user"
	"github.com/perfect-panel/server/pkg/xerr"
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

// HasPaidSubscription reports whether the user owns at least one paid
// subscription record — order-backed (order_id > 0) or Apple-IAP-backed
// (token LIKE 'iap:%'). Returns false when userID or db are not usable so
// callers can fall back to the "first purchase" branch safely.
//
// This mirrors the predicate used to route /v1/public/order/purchase requests
// to renewal semantics. Keep both in sync.
func HasPaidSubscription(ctx context.Context, db *gorm.DB, userID int64) (bool, error) {
	if userID <= 0 || db == nil {
		return false, nil
	}

	var count int64
	if err := db.WithContext(ctx).
		Model(&user.Subscribe{}).
		Where("user_id = ? AND (order_id > 0 OR token LIKE 'iap:%')", userID).
		Limit(1).
		Count(&count).Error; err != nil {
		return false, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query paid subscription failed: %v", err.Error())
	}
	return count > 0, nil
}
