<?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
    {
        // Handle both 'name' and 'first_name'/'last_name' formats
        if ($request->has('name')) {
            $nameParts = explode(' ', trim($request->validated('name')), 2);
            $firstName = $nameParts[0];
            $lastName = $nameParts[1] ?? null;
        } else {
            $firstName = $request->validated('first_name');
            $lastName = $request->validated('last_name');
        }

        $user = User::create([
            'first_name' => $firstName,
            'last_name' => $lastName,
            '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,
        );
    }
}
