package users

import (
	"log"
	"strings"

	"git.ali33.ru/fcg-xvii/go-tools/json"
	"git.ali33.ru/fcg-xvii/rest"
	"git.ali33.ru/fcg-xvii/rest/example_chat/chat"
)

type Register struct {
	Name     string `rest:"require"`
	Password string `rest:"require"`
}

func (s *Register) Validate(req rest.IRequest) rest.IResponse {
	log.Println(s.Name, s.Password)
	s.Name = strings.TrimSpace(s.Name)
	if len(s.Name) < 3 {
		return req.ResponseError(500, rest.ErrorFiled("name", "minimum 3 symbols"))
	}
	if len(s.Password) < 5 {
		return req.ResponseError(500, rest.ErrorFiled("name", "minimum 5 symbols"))
	}
	return nil
}

func (s *Register) Execute(req rest.IRequest) rest.IResponse {
	core := req.Core().(*chat.Chat)
	user := core.Register(s.Name, s.Password)
	fields, err := rest.Fields(user, nil)
	if err != nil {
		return req.ResponseError(500, err)
	}
	req.SetAuth(json.Map{
		"user": user,
	})
	return req.ResponseSuccess(fields, nil)
}
