<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Http\Requests\Auth\RegisterRequest;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function register(RegisterRequest $request): JsonResponse
    {
        $email = (string) $request->string('email');
        $name = (string) ($request->string('name')->toString() ?: '');

        if ($name === '') {
            $name = strtok($email, '@') ?: 'User';
        }

        $user = User::create([
            'name' => $name,
            'email' => $email,
            'password' => Hash::make((string) $request->string('password')),
        ]);

        $token = auth('api')->login($user);

        return $this->respondWithToken($token, 'User registered');
    }

    public function login(LoginRequest $request): JsonResponse
    {
        $credentials = $request->only(['email', 'password']);

        if (! $token = auth('api')->attempt($credentials)) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid credentials',
                'data' => null,
            ], 401);
        }

        return $this->respondWithToken($token, 'Login successful');
    }

    public function me(): JsonResponse
    {
        return response()->json([
            'success' => true,
            'message' => 'User profile',
            'data' => auth('api')->user(),
        ]);
    }

    public function logout(): JsonResponse
    {
        auth('api')->logout();

        return response()->json([
            'success' => true,
            'message' => 'Logged out',
            'data' => null,
        ]);
    }

    public function refresh(): JsonResponse
    {
        return $this->respondWithToken(auth('api')->refresh(), 'Token refreshed');
    }

    private function respondWithToken(string $token, string $message): JsonResponse
    {
        return response()->json([
            'success' => true,
            'message' => $message,
            'data' => [
                'access_token' => $token,
                'token_type' => 'bearer',
                'expires_in' => auth('api')->factory()->getTTL() * 60,
                'user' => auth('api')->user(),
            ],
        ]);
    }
}
