<?php

namespace App\Http\Controllers\Admin\Api;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Auth\LoginRequest;
use App\Services\Admin\AuthService;
use App\libs\Response\GlobalApiResponse;
use App\libs\Response\GlobalApiResponseCodeBook;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    private $authService;

    public function __construct(AuthService $authService) {
        $this->authService = $authService;
    }

    public function login(LoginRequest $loginRequest){
        $token = $this->authService->login($loginRequest->all());
        if($this->authService->hasError())
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_CREDENTIALS,'Invalid email or password',$this->authService->getErrors());
        $result = [
            'token' => session()->get('_token')
        ];
        Auth::user()->update(['last_login' => Carbon::now()]);
        return (new GlobalApiResponse())->success('Successfully logged in',1,$result);
    }

    public function logout()
    {
        $this->authService->logout();
        return (new GlobalApiResponse())->success('Successfully logged out',1);
    }
}
