package chat

import (
	"sync"
	"sync/atomic"
)

func New() *Chat {
	res := &Chat{
		users:     &sync.Map{},
		idCounter: &atomic.Int64{},
	}
	return res
}

type Chat struct {
	users     *sync.Map
	idCounter *atomic.Int64
}

func (s *Chat) Register(name, password string) *User {
	user := &User{
		ID:       s.idCounter.Add(1),
		Name:     name,
		Password: password,
	}
	s.users.Store(user.ID, user)
	return user
}

func (s *Chat) SearchByID(id int64) (*User, bool) {
	if u, check := s.users.Load(id); check {
		return u.(*User), true
	}
	return nil, false
}

func (s *Chat) Auth(name, password string) (res *User, check bool) {
	s.users.Range(func(key, val any) bool {
		u := val.(*User)
		if u.Name == name && u.Password == password {
			res, check = u, true
			return false
		}
		return true
	})
	return
}
