<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function login(Request $request): JsonResponse
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (!Auth::attempt($credentials)) {
            return response()->json(['message' => 'Неверные данные'], 401);
        }

        $user = $request->user();
        $token = $user->createToken('react-native-token')->plainTextToken;

        return response()->json([
            'token' => $token,
            'user' => $user,
        ]);
    }

    public function logout(Request $request): JsonResponse
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json(['message' => 'Выход выполнен']);
    }

    public function savePushToken(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'expo_push_token' => 'required|string|max:255',
        ]);

        $user = $request->user();
        $user->expo_push_token = $validated['expo_push_token'];
        $user->save();

        return response()->json(['message' => 'Push-токен сохранён']);
    }
}
