<?php

namespace App\Http\Controllers\Api;

use App\Actions\LoginUserAction;
use App\Actions\LogoutUserAction;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\LoginRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class AuthController extends Controller
{
    public function __construct(
        private LoginUserAction $loginUser,
        private LogoutUserAction $logoutUser,
    ) {}

    public function login(LoginRequest $request): JsonResponse
    {
        $user = $this->loginUser->handle($request, $request->credentials());

        return UserResource::make($user->loadMissing('role.permissions'))->response();
    }

    public function logout(Request $request): Response
    {
        $this->logoutUser->handle($request);

        return response()->noContent();
    }

    public function me(Request $request): JsonResponse
    {
        $user = $request->user();

        assert($user instanceof User);

        return UserResource::make($user->loadMissing('role.permissions'))->response();
    }
}
