<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterRequest;
use App\Http\Resources\AuthResource;
use App\Models\User;
use Illuminate\Http\Response;

class RegisterController extends Controller
{
    public function register(RegisterRequest $request): Response
    {
        $user = User::create([
            'first_name' => $request->validated('first_name'),
            'last_name' => $request->validated('last_name'),
            'email' => $request->validated('email'),
            'phone' => $request->validated('phone'),
            'password' => $request->validated('password'),
        ]);

        if ($request->hasAny(['gender', 'birth_date', 'city', 'interests', 'settings'])) {
            $user->profile()->create([
                'gender' => $request->validated('gender'),
                'birth_date' => $request->validated('birth_date'),
                'city' => $request->validated('city'),
                'interests' => $request->validated('interests'),
                'settings' => $request->validated('settings'),
            ]);
        }

        $accessToken = $user->createToken('auth-token');

        return response(
            new AuthResource([
                'user' => $user,
                'access_token' => $accessToken->plainTextToken,
                'expires_at' => null,
            ]),
            Response::HTTP_CREATED,
        );
    }
}
