<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

/**
 * Emissione e revoca token Sanctum (vedi documentazione API Token Authentication).
 *
 * @see https://laravel.com/docs/12.x/sanctum#api-token-authentication
 */
class TokenAuthController extends Controller
{
    /**
     * Scambia email/password con un token personale (per agent, app mobili, ecc.).
     */
    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
            'device_name' => ['required', 'string', 'max:255'],
        ]);

        $user = User::query()->where('email', $data['email'])->first();

        if (! $user || ! Hash::check($data['password'], $user->password)) {
            throw ValidationException::withMessages([
                'email' => [__('Credenziali non valide.')],
            ]);
        }

        // Abilità del token: restringi quando avrai route dedicate (es. solo stampa:poll).
        $abilities = ['stampa'];

        $token = $user->createToken($data['device_name'], $abilities);

        return response()->json([
            'token' => $token->plainTextToken,
            'token_type' => 'Bearer',
            'user' => [
                'id' => $user->id,
                'nome' => $user->nome,
                'cognome' => $user->cognome,
                'email' => $user->email,
            ],
        ]);
    }

    /**
     * Utente corrente (utile per verificare che il Bearer sia valido).
     */
    public function user(Request $request): JsonResponse
    {
        return response()->json($request->user());
    }

    /**
     * Revoca il token usato per la richiesta corrente.
     */
    public function destroy(Request $request): JsonResponse
    {
        $request->user()->currentAccessToken()?->delete();

        return response()->json(['message' => 'Token revocato.']);
    }
}
