package discord

import (
	"net/http"
	"sync"
	"time"

	"git.haelnorr.com/h/golib/hlog"
	"github.com/bwmarrin/discordgo"
	"github.com/pkg/errors"
)

type OAuthSession struct {
	*discordgo.Session
}

func NewOAuthSession(token *Token) (*OAuthSession, error) {
	session, err := discordgo.New("Bearer " + token.AccessToken)
	if err != nil {
		return nil, errors.Wrap(err, "discordgo.New")
	}
	return &OAuthSession{Session: session}, nil
}

func (s *OAuthSession) GetUser() (*discordgo.User, error) {
	user, err := s.User("@me")
	if err != nil {
		return nil, errors.Wrap(err, "s.User")
	}
	return user, nil
}

// APIClient is an HTTP client wrapper that handles Discord API rate limits
type APIClient struct {
	cfg         *Config
	client      *http.Client
	logger      *hlog.Logger
	mu          sync.RWMutex
	buckets     map[string]*RateLimitState
	trustedHost string
}

// NewAPIClient creates a new Discord API client with rate limit handling
func NewAPIClient(cfg *Config, logger *hlog.Logger, trustedhost string) (*APIClient, error) {
	if cfg == nil {
		return nil, errors.New("config cannot be nil")
	}
	if logger == nil {
		return nil, errors.New("logger cannot be nil")
	}
	if trustedhost == "" {
		return nil, errors.New("trustedhost cannot be empty")
	}
	return &APIClient{
		client:      &http.Client{Timeout: 30 * time.Second},
		logger:      logger,
		buckets:     make(map[string]*RateLimitState),
		cfg:         cfg,
		trustedHost: trustedhost,
	}, nil
}
