<?php

namespace App\Http\Controllers;

use App\Http\Resources\UserTypeResource;
use App\Services\UserService;
use App\Http\Requests\UserRequest;
use App\Http\Requests\UpdateMeRequest;
use App\Http\Resources\UserResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class UserController extends Controller
{
  public function __construct(protected UserService $service) {}

  public function me(): JsonResponse
  {
    $user = $this->service->me();
    return $this->successResponse(payload: new UserResource($user));
  }

  public function index(): JsonResponse
  {
    $items = $this->service->getAll();
    return $this->successResponse(
      payload: UserResource::collection($items),
    );
  }

  public function store(UserRequest $request): JsonResponse
  {
    $item = $this->service->create($request->validated());
    return $this->successResponse(
      payload: new UserResource($item),
      message: __("messages.created"),
      code: 201,
    );
  }

  public function show(int $id): JsonResponse
  {
    $item = $this->service->findById($id);
    return $this->successResponse(payload: new UserResource($item));
  }

  public function update(UserRequest $request, int $id): JsonResponse
  {
    $item = $this->service->update($id, $request->validated());
    return $this->successResponse(
      payload: new UserResource($item),
      message: __("messages.updated"),
    );
  }

  public function destroy(int $id): JsonResponse
  {
    $this->service->delete($id);
    return $this->successResponse(
      message: __("messages.deleted"),
      code: 204,
    );
  }

  public function updateMe(UpdateMeRequest $request): JsonResponse
  {
    $user = $this->service->updateMe($request->validated());
    return $this->successResponse(
      payload: new UserResource($user),
      message: __("messages.updated"),
    );
  }

  public function getUserTypes(): JsonResponse
  {
    $user_types = $this->service->getUserTypes();
    return $this->successResponse(
      payload: new UserTypeResource($user_types),
    );
  }
}
