package adminservice

import (
	"context"

	"git.gocasts.ir/ebhomengo/niki/entity"
	adminserviceparam "git.gocasts.ir/ebhomengo/niki/param/admin/admin"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)

func (s Service) Register(ctx context.Context, req adminserviceparam.RegisterRequest) (adminserviceparam.RegisterResponse, error) {
	const op = richerror.Op("adminservice.Register")

	var newAdmin entity.Admin
	if req.FirstName != nil {
		newAdmin.FirstName = *req.FirstName
	}
	if req.LastName != nil {
		newAdmin.LastName = *req.LastName
	}
	if req.PhoneNumber != nil {
		newAdmin.PhoneNumber = *req.PhoneNumber
	}
	if req.Role != nil {
		newAdmin.Role = *req.Role
	}
	if req.Description != nil {
		newAdmin.Description = *req.Description
	}
	if req.Email != nil {
		newAdmin.Email = *req.Email
	}
	if req.Gender != nil {
		newAdmin.Gender = *req.Gender
	}
	if req.Status != nil {
		newAdmin.Status = *req.Status
	}

	if bErr := GenerateHash(req.Password); bErr != nil {
		return adminserviceparam.RegisterResponse{}, richerror.New(op).WithErr(bErr).WithKind(richerror.KindUnexpected)
	}
	newAdmin.Password = *req.Password

	admin, err := s.repo.AddAdmin(ctx, newAdmin)
	if err != nil {
		return adminserviceparam.RegisterResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
	}

	return adminserviceparam.RegisterResponse{Admin: admin}, err
}
