<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterUserRequest;
use App\Models\User;
use App\Services\SignatureService;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\Support\Str;
use Illuminate\Http\JsonResponse;
use App\Http\Resources\UserResource;

class RegisteredUserController extends Controller
{
    /**
     * Создать нового пользователя.
     */
    public function store(RegisterUserRequest $request): JsonResponse
    {
        $data = $request->validated();     // массив, а не объект!

        // 1. Создаём пользователя
        $user = User::create([
            'login'         => $data['login'],
            'password'      => Hash::make($data['password']),
            'first_name'    => $data['first_name'],
            'last_name'     => $data['last_name'],
            'middle_name'   => $data['middle_name'],
            'role_id'       => $data['role_id'],
            'position'      => $data['position'],
            'birthday'      => $data['birthday'],
            'token'         => Str::random(60),
            'refresh_token' => Str::random(60),
            'is_active'     => true,
        ]);

        // 2. Генерируем и сохраняем ключи
        $keys = SignatureService::generateUserKeys();
        $user->update([
            'public_key'  => $keys['publicKey'],
            'private_key' => $keys['privateKey'],
        ]);

        event(new Registered($user));

        // 3. Отдаём 201 Created и созданного пользователя
        return response()->json([
            'message' => 'Пользователь успешно зарегистрирован',
            'user'    => new UserResource($user),
        ], 201);
    }
}
