package bot

import (
	"context"
	"fmt"
	"strings"
	"sync"
	"time"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"

	"github.com/z/tg-apicreator-bot/internal/config"
	"github.com/z/tg-apicreator-bot/internal/database"
	"github.com/z/tg-apicreator-bot/internal/logging"
	"github.com/z/tg-apicreator-bot/internal/mytelegram"
	"github.com/z/tg-apicreator-bot/internal/proxy"
	"github.com/z/tg-apicreator-bot/internal/ratelimit"
	"github.com/z/tg-apicreator-bot/internal/repository"
)

// state is the per-user FSM state for the key-creation flow.
type state int

const (
	stateIdle state = iota
	stateAwaitPhone
	stateAwaitOTP
)

// session holds the in-progress creation flow for one user.
type session struct {
	state      state
	phone      string
	randomHash string
	proxy      mytelegram.Proxy
	proxyID    int64
	startedAt  time.Time
}

// Bot is the long-running Telegram bot. It owns the api client, the shared
// repository, the proxy manager, the rate limiter and the per-user sessions.
type Bot struct {
	api     *tgbotapi.BotAPI
	cfg     *config.Config
	repo    *repository.Repository
	proxies *proxy.Manager
	limiter *ratelimit.Limiter
	logger  *logging.Logger

	mu       sync.RWMutex
	sessions map[int64]*session
}

// New constructs the bot, connects to Telegram and validates the token.
func New(cfg *config.Config, repo *repository.Repository, pm *proxy.Manager, lim *ratelimit.Limiter, lg *logging.Logger) (*Bot, error) {
	api, err := tgbotapi.NewBotAPI(cfg.Bot.Token)
	if err != nil {
		return nil, fmt.Errorf("connect telegram: %w", err)
	}
	api.Debug = false
	lg.Infof("bot", "authorized as @%s (%s)", api.Self.UserName, api.Self.FirstName)

	return &Bot{
		api:      api,
		cfg:      cfg,
		repo:     repo,
		proxies:  pm,
		limiter:  lim,
		logger:   lg,
		sessions: map[int64]*session{},
	}, nil
}

// Start blocks on the update channel and dispatches every update. It returns
// when ctx is cancelled or the update channel is closed.
func (b *Bot) Start(ctx context.Context) error {
	u := tgbotapi.NewUpdate(0)
	u.Timeout = 30
	updates := b.api.GetUpdatesChan(u)

	for {
		select {
		case <-ctx.Done():
			b.logger.Infof("bot", "shutting down: %v", ctx.Err())
			return ctx.Err()
		case upd, ok := <-updates:
			if !ok {
				return nil
			}
			// Each update is handled inline; the bot api is goroutine-safe
			// but keeping processing serial avoids races on sessions.
			b.dispatch(upd)
		}
	}
}

// dispatch fans an update out to the right handler.
func (b *Bot) dispatch(update tgbotapi.Update) {
	// Callback queries take priority: they may arrive without a Message.
	if update.CallbackQuery != nil {
		b.handleCallback(update)
		return
	}
	if update.Message == nil {
		return
	}
	msg := update.Message

	// Refresh the user's profile / last_seen on every message.
	if msg.From != nil {
		_, _ = b.repo.UpsertUser(database.User{
			TgID:      msg.From.ID,
			Username:  msg.From.UserName,
			FirstName: msg.From.FirstName,
			LastName:  msg.From.LastName,
			IsAdmin:   b.cfg.IsAdmin(msg.From.ID),
		})
	}

	if msg.IsCommand() {
		b.handleCommand(update)
		return
	}

	// Non-command text: route to the active session (phone / otp input).
	b.handleSessionText(update)
}

// ---- session helpers ----

func (b *Bot) session(uid int64) *session {
	b.mu.RLock()
	s := b.sessions[uid]
	b.mu.RUnlock()
	if s != nil {
		return s
	}
	s = &session{state: stateIdle}
	b.mu.Lock()
	b.sessions[uid] = s
	b.mu.Unlock()
	return s
}

func (b *Bot) setState(uid int64, st state) {
	s := b.session(uid)
	b.mu.Lock()
	s.state = st
	b.mu.Unlock()
}

func (b *Bot) resetSession(uid int64) {
	b.mu.Lock()
	delete(b.sessions, uid)
	b.mu.Unlock()
}

// logf is a convenience wrapper used by middleware/handlers.
func (b *Bot) logf(level, format string, args ...any) {
	switch strings.ToLower(level) {
	case "warn", "warning":
		b.logger.Warnf("bot", format, args...)
	case "error", "err":
		b.logger.Errorf("bot", format, args...)
	case "debug":
		// not surfaced by default; kept for future use
	default:
		b.logger.Infof("bot", format, args...)
	}
}

// newUserFromUpdate builds a database.User skeleton from an update (used when
// a previously-unseen user triggers the access guard).
func (b *Bot) newUserFromUpdate(update tgbotapi.Update, isAdmin bool) database.User {
	uid := userIDOf(update)
	var uname, first, last string
	switch {
	case update.Message != nil && update.Message.From != nil:
		uname = update.Message.From.UserName
		first = update.Message.From.FirstName
		last = update.Message.From.LastName
	case update.CallbackQuery != nil && update.CallbackQuery.From != nil:
		uname = update.CallbackQuery.From.UserName
		first = update.CallbackQuery.From.FirstName
		last = update.CallbackQuery.From.LastName
	}
	return database.User{
		TgID:         uid,
		Username:     uname,
		FirstName:    first,
		LastName:     last,
		Language:     b.cfg.Bot.DefaultLanguage,
		IsAdmin:      isAdmin,
	}
}

// Me exposes the bot's own username (used by the web panel for a deep link).
func (b *Bot) Me() string {
	if b.api != nil {
		return "@" + b.api.Self.UserName
	}
	return ""
}
