<?php

namespace App\Modules\User\Http\Controllers\Auth;

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


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

        $user = User::where('email', $request->email)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->error('Invalid credentials', [], 401);
        }

        //$user->tokens()->delete();
        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->success('Login successful', [
            'access_token' => 'Bearer ' . $token,
            'user' => $user,
        ]);
    }

    /**
     * Handle user logout.
     */
    public function logout(Request $request)
    {
        $request->user()->tokens()->delete();

        return response()->success('Logout successful', []);
    }

    public function test(Request $request)
    {
        $user = $request->user();
        return response()->success('Test successful', [$user]);
    }
}
