<?php

namespace App\Http\Controllers;

use App\Http\Requests\Auth\LoginRequest;
use App\Http\Traits\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    use ApiResponse;

    public function login(LoginRequest $request): JsonResponse
    {
        if ($this->attemptLogin($request))
        {
            $request->session()->regenerate();
            $this->updateUserInfo($request);
            return $this->successResponse();
        }

        return $this->errorResponse(__('messages.invalid_credentials'));
    }

    protected function attemptLogin(Request $request): bool
    {
        return Auth::guard()->attempt($request->only('username', 'password'));
    }

    protected function updateUserInfo(Request $request): void
    {
        Auth::user()->update([
            'last_login' => now(),
        ]);
    }

    public function logout(Request $request): JsonResponse
    {
        Auth::guard()->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return $this->successResponse();
    }
}
