package usersvc

import (
	"errors"
	"log"

	hqi "dev.hexasoftware.com/hxs/hqi.git"

	"github.com/google/uuid"
)

type Service struct {
	q hqi.Query
}

func New(q hqi.Query) *Service {
	// Reusable session
	return &Service{q}
}

func (s *Service) NewUser(name string, desc string, email string, password string) error {

	{
		var res []User
		s.q.Find(hqi.M{"Name": name}).
			List(&res)
		if len(res) > 0 {
			return errors.New("User name Already exists")
		}
	}
	{
		var res []User
		s.q.Find(hqi.M{"Accounts": hqi.M{"Kind": "email", "Data": hqi.M{"email": email}}}).
			List(&res)

		if len(res) > 0 {
			return errors.New("User Email Already exists")
		}
	}

	nUser := User{
		ID:          uuid.New().String(),
		Name:        name,
		Description: desc,
		Accounts: []UserAccount{{
			Kind: "email",
			Data: map[string]string{"email": email, "pwd": password},
		}},
	}
	return s.q.Insert(&nUser)
}

//Login entry can be email, username, mobilephone
func (s *Service) Login(entry string, password string) (*User, error) {
	byName := User{
		Name: entry,
		Accounts: []UserAccount{
			{Kind: "email", Data: map[string]string{"pwd": password}},
		},
	}
	// Above should be Name entry email password AND test 1
	//log.Println("byName:", byName)

	/*hqi.M{
		"Name":     entry,
		"Accounts": hqi.M{"Kind": "email", "Data": hqi.M{"pwd": password}},
	}*/
	/*byEmail := hqi.M{
		"Accounts": hqi.M{
			"Kind": "email",
			"Data": hqi.M{
				"email": entry,
				"pwd":   password,
			},
		},
	}*/
	var res []User
	err := s.q.Find(byName).List(&res)
	if err != nil {
		return nil, err
	}
	log.Println("Login:", res)
	if len(res) == 0 {
		return nil, errors.New("Not found")
	}
	if len(res) > 1 {
		return nil, errors.New("Result should be 1")
	}

	return &res[0], nil
}

func (s *Service) MustList() []User {
	var res []User
	err := s.q.Find().List(&res)
	if err != nil {
		panic(err)
	}

	return res
}
