package user

import (
	"gitea.frenchtouch.duckdns.org/kratisto/budget-backend/internal/storage/dao"
	"gitea.frenchtouch.duckdns.org/kratisto/budget-backend/internal/storage/model"
)

type Service struct {
	db *Database
}

func NewService(database *Database) *Service {
	return &Service{db: database}
}

func (s *Service) GetUserById(userId string) (*User, error) {
	user, err := s.db.GetUsersByID(userId)
	if e, ok := err.(*dao.Error); ok {
		switch e.Type {
		case dao.ErrTypeNotFound:
			return nil, &model.ErrNotFound
		default:
			return nil, &model.ErrInternalServer
		}
	} else if err != nil {
		return nil, &model.ErrInternalServer
	}

	if user == nil {
		return nil, &model.ErrNotFound
	}
	return user, nil
}

func (us *Service) GetUserFromGoogleID(googleUserID string) (*User, error) {
	user, err := us.db.GetUsersByGoogleID(googleUserID)
	if err != nil {
		if castedError, ok := err.(*dao.Error); ok {
			switch castedError.Type {
			case dao.ErrTypeNotFound:
				return nil, &model.ErrNotFound
			default:
				return nil, &model.ErrInternalServer
			}
		}
		return nil, &model.ErrInternalServer
	}
	return user, nil
}

func (us *Service) CreateUserFromGoogleToken(id string, email string) (*User, error) {
	user := &User{UserEditable: UserEditable{Email: email}, GoogleID: id}
	err := us.db.CreateUser(user)
	return user, err
}
