<?php

namespace App\Http\Controllers\Auth;

use App\Contracts\AuthServiceInterface;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Http\Resources\Auth\UserAuthResource;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\JsonResponse;

class AuthenticatedSessionController extends Controller
{
    protected $service;

    public function __construct( AuthServiceInterface $service)
    {
        $this->service = $service;
    }
    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): JsonResponse
    {
        $user = $this->service->authenticate($request);
        $user->load('roles');
        
        return (new UserAuthResource($user))
                ->additional(['token' => $this->service->createStringAuthToken($request->user())])
                ->response()
                ->setStatusCode(200);            
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): Response
    {
        $this->service->logout($request);
        return response()->noContent();
    }
}
