<?php

namespace App\Domains\UserManagement\Controllers;

use App\Domains\MessageSystem\Actions\SendMessage\SendMessageCommand;
use App\Domains\MessageSystem\Actions\SendMessage\SendMessageRequest;
use App\Domains\UserManagement\Actions\UserRegistration\UserRegistrationCommand;
use App\Domains\UserManagement\Actions\UserRegistration\UserRegistrationRequest;
use App\Enumerations\MessageType;
use App\Enumerations\UserRole;
use App\Providers\InertiaProvider;
use App\Scopes\CommonController;
use App\ValueObjects\EmailAddress;
use App\ValueObjects\MessageRecipient;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RegistrationController extends CommonController {
    public function loginForm(Request $request) {
        $errors = [];

        if ($request->session()->has('errors')) {
            $errors = $request->session()->get('errors')->getBag('default')->getMessages();
        }


        $inertiaProvider = new InertiaProvider('UserManagement/Registration', [
            'errors' => $errors,
            'appName' => app('tenant')->name,
            'tenant' => app('tenant'),
        ]);
        return $inertiaProvider->render();
    }

    public function doRegistration(Request $request) : JsonResponse {

        $user = $this->users->findByUsername($request->get('email'));
        if ($user !== null) {
            return response()->json([
                'status' => 'error',
                'message' => 'Dieser Account existiert bereits.'
            ]);
        }

        $email = EmailAddress::fromString($request->get('email'));
        $userRoleMain = UserRole::USER_ROLE_USER;
        $userRoleLocalGroup = UserRole::USER_ROLE_USER;

        $localGroup = app('tenant')->slug === 'lv' ? $request->get('localGroup') : app('tenant')->slug;


        $registrationRequest = new UserRegistrationRequest(
            $request->get('firstname'),
            $request->get('lastname'),
            $request->get('nickname'),
            $email,
            $userRoleMain,
            $userRoleLocalGroup,
            $localGroup
        );

        $registrationCommand = new UserRegistrationCommand($registrationRequest);
        $result = $registrationCommand->execute();

        if (!$result->success) {
            return response()->json([
                'status' => 'error',
                'message' => 'Beim Erstellen des Accounts ist ein Fehler aufgetreten.'
            ]);
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Registrierung erfolgreich! Bitte prüfe nun dein E-Mail-Postfach'
        ]);
    }
}
