<?php

namespace App\Http\Controllers\Api\Auth;

use App\Models\User;
use App\RequestRules\Api\UserRules;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;

class RegisterController extends AuthenticateController
{
    /**
     * Register new user
     *
     * @param Request $request
     * @return Response|Application|ResponseFactory
     * @throws ValidationException
     */
    public function register(Request $request): Response|Application|ResponseFactory
    {
        $this->validate($request, UserRules::registrationRules());

        if(! filled($request->{'telephone'})) {
            return api_response(150, __('errors.enter_telephone_or_email'));
        }

        try {
           /** @var User $user */
            $user = User::registerUser($request->all(), $request->allFiles());

            if($user !== null) {
                return $this->respondWithToken(
                    user: $user->refresh(),
                    data: ["user" => self::responseWithUser($user)],
                );
            }
        } catch (\Exception $exception) {
            log_debug(exception: $exception,  prefix: 'RegisterController::register');
        }

        return api_response(101, __('errors.unknown_error'));
    }
}
