package authsvc

import (
	"errors"

	authdomain "legalgo-BE-go/internal/domain/auth"
	userdomain "legalgo-BE-go/internal/domain/user"
	"legalgo-BE-go/internal/utilities/utils"

	"github.com/google/uuid"
)

func (a *impl) RegisterUser(spec userdomain.UserRegister) (string, error) {
	_, err := a.userRepo.GetUserByEmail(spec.Email)

	if err == nil {
		return "", errors.New("this email address is already in use")
	}

	if spec.SubscribePlanID == "" {
		subsPlan, err := a.subsPlanRepo.GetDefault()
		if err != nil {
			return "", err
		}

		spec.SubscribePlanID = subsPlan.ID
	}

	_, err = a.subsPlanRepo.GetByID(spec.SubscribePlanID)
	if err != nil {
		return "", errors.New(err.Error())
	}

	subsId, err := a.subsRepo.Create(spec.SubscribePlanID)
	if err != nil {
		return "", err
	}

	hashedPwd, err := HashPassword(spec.Password)
	if err != nil {
		return "", err
	}

	user := userdomain.User{
		ID:          uuid.NewString(),
		Email:       spec.Email,
		SubscribeID: subsId,
		Password:    hashedPwd,
		Phone:       spec.Phone,
	}

	err = a.userRepo.CreateUser(user)
	if err != nil {
		return "", errors.New(err.Error())
	}

	authToken := authdomain.AuthToken{
		Email:     user.Email,
		SessionID: uuid.NewString(),
		Role:      "user",
	}

	token, err := utils.GenerateToken(authToken)
	if err != nil {
		return "", errors.New(err.Error())
	}
	return token, nil
}
