<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Auth;

use App\Http\Controllers\Api\V1\Auth\Concerns\IssuesAuthentication;
use App\Http\Requests\Auth\RegisterRequest;
use App\Http\Resources\UserResource;
use App\Services\Users\UserRegistrar;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller;
use Symfony\Component\HttpFoundation\Response;

final class RegisteredUserController extends Controller
{
    use IssuesAuthentication;

    public function __construct(
        private readonly UserRegistrar $registrar,
    ) {}

    public function store(RegisterRequest $request): JsonResponse
    {
        $user = $this->registrar->register([
            'name' => $request->string('name')->toString(),
            'email' => $request->string('email')->toString(),
            'password' => $request->string('password')->toString(),
            'phone' => $request->input('phone'),
            'locale' => $request->input('locale'),
            'timezone' => $request->input('timezone'),
            'marketing_opt_in' => $request->boolean('marketing_opt_in'),
        ]);

        /*
         * Signed in immediately so registration flows straight into the app --
         * a cookie session for the SPA, a bearer token for a named device.
         */
        $token = $this->issueAuthentication($request, $user);

        return response()->json([
            'message' => 'Account created. Check your inbox to confirm your email address.',
            'user' => UserResource::make($user->load(['profile'])),
            'token' => $token,
        ], Response::HTTP_CREATED);
    }
}
