<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login(Request $request) {
        $request->validate(['email'=>'required|email','password'=>'required|string','device_name'=>'nullable|string|max:100']);
        $user = User::where('email', $request->email)->first();
        if (!$user || !Hash::check($request->password, $user->password))
            throw ValidationException::withMessages(['email' => ['Credenciales incorrectas.']]);
        $device = $request->device_name ?? 'api-token';
        $user->tokens()->where('name', $device)->delete();
        $token = $user->createToken($device, ['*'], now()->addDays(30));
        return response()->json(['success'=>true,'data'=>['token'=>$token->plainTextToken,'token_type'=>'Bearer','expires_at'=>$token->accessToken->expires_at?->toIso8601String(),'user'=>new UserResource($user)]]);
    }
    public function logout(Request $request) {
        $request->user()->currentAccessToken()->delete();
        return response()->json(['success'=>true,'message'=>'Sesión cerrada.']);
    }
    public function logoutAll(Request $request) {
        $request->user()->tokens()->delete();
        return response()->json(['success'=>true,'message'=>'Todas las sesiones cerradas.']);
    }
    public function me(Request $request) {
        return response()->json(['success'=>true,'data'=>new UserResource($request->user()->load('department'))]);
    }
    public function tokens(Request $request) {
        return response()->json(['success'=>true,'data'=>$request->user()->tokens()->select(['id','name','last_used_at','expires_at','created_at'])->get()]);
    }
}
