// Package proxy rotates through the proxies stored in the database and hands
// out mytelegram.Proxy values to the my.telegram.org client.
package proxy

import (
	"sync"
	"sync/atomic"

	"github.com/z/tg-apicreator-bot/internal/database"
	"github.com/z/tg-apicreator-bot/internal/mytelegram"
	"github.com/z/tg-apicreator-bot/internal/repository"
)

// Manager keeps an in-memory snapshot of enabled proxies and round-robins
// them. Reload() is called whenever the admin edits the proxy table.
type Manager struct {
	repo *repository.Repository

	mu      sync.RWMutex
	proxies []database.Proxy
	cursor  uint64
}

func New(repo *repository.Repository) *Manager {
	return &Manager{repo: repo}
}

// Reload refreshes the in-memory snapshot from the database.
func (m *Manager) Reload() error {
	ps, err := m.repo.ListEnabledProxies()
	if err != nil {
		return err
	}
	m.mu.Lock()
	m.proxies = ps
	m.mu.Unlock()
	return nil
}

// Next returns the next proxy in round-robin order, or a "none" proxy when
// the list is empty. If markFailed is true the manager bumps the proxy's
// fail counter; otherwise it resets it.
func (m *Manager) Next() mytelegram.Proxy {
	m.mu.RLock()
	defer m.mu.RUnlock()

	if len(m.proxies) == 0 {
		return mytelegram.Proxy{Kind: "none"}
	}
	idx := atomic.AddUint64(&m.cursor, 1) - 1
	p := m.proxies[idx%uint64(len(m.proxies))]
	return mytelegram.Proxy{
		Kind:     p.Kind,
		Host:     p.Host,
		Port:     p.Port,
		Username: p.Username,
		Password: p.Password,
	}
}

// MarkUsed reports the outcome of using the last proxy returned by Next so
// fail counters stay accurate. Safe to ignore the error.
func (m *Manager) MarkUsed(id int64, failed bool) {
	_ = m.repo.MarkProxyUsed(id, failed)
	if failed {
		// Refresh lazily so a permanently dead proxy falls out of rotation.
		_ = m.Reload()
	}
}

// NextWithID returns the next enabled proxy together with its database id,
// so callers can report usage outcome via MarkUsed. When the rotation is
// empty, id is 0 and the proxy is "none".
func (m *Manager) NextWithID() (mytelegram.Proxy, int64) {
	m.mu.RLock()
	defer m.mu.RUnlock()

	if len(m.proxies) == 0 {
		return mytelegram.Proxy{Kind: "none"}, 0
	}
	idx := atomic.AddUint64(&m.cursor, 1) - 1
	p := m.proxies[idx%uint64(len(m.proxies))]
	return mytelegram.Proxy{
		Kind:     p.Kind,
		Host:     p.Host,
		Port:     p.Port,
		Username: p.Username,
		Password: p.Password,
	}, p.ID
}

// Count reports how many enabled proxies are in rotation.
func (m *Manager) Count() int {
	m.mu.RLock()
	defer m.mu.RUnlock()
	return len(m.proxies)
}
