package usersvc

import (
	"fmt"
	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 (i *impl) RegisterUser(spec userdomain.UserRegister) (string, error) {
	_, err := i.userRepo.GetUserByEmail(spec.Email)

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

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

		spec.SubscribePlanID = subsPlan.ID
	}

	_, err = i.subsPlanRepo.GetByID(spec.SubscribePlanID)
	if err != nil {
		return "", err
	}

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

	hashedPwd, err := utils.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 = i.userRepo.CreateUser(user)
	if err != nil {
		return "", fmt.Errorf("create user failed: %v", err)
	}

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

	token, err := utils.GenerateToken(authToken)
	if err != nil {
		return "", fmt.Errorf("generate token failed: %v", err)
	}
	return token, nil
}
