<?php

namespace App\Http\Controllers;

use Illuminate\Support\Arr;
use App\Services\UserService;
use App\Http\Resources\UsersList;
use App\Http\Resources\UserResource;
use App\Http\Requests\User\UserStore;
use App\Http\Resources\UserLoggedResource;

class UserController extends Controller
{

    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
        $this->middleware('auth:sanctum');
    }

    public function index()
    {
        $users = $this->userService->getWith(['roles']);

        return response()->json(UserResource::collection($users), 200);
    }

    public function show($id)
    {
        $isAdmin = auth()->user()->hasRole('admin');
        $isTheUserOwner = auth()->user()->id === (int) $id;

        if (!$isAdmin && !$isTheUserOwner) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $user = $this->userService->getOneWith($id, ['roles']);

        if ($user) {
            return response()->json(new UserResource($user));
        } else  return response()->json(['message' => 'User not found.'], 404);
    }

    public function store(UserStore $request)
    {
        $isSuperAdmin = auth()->user()->hasRole('super_admin');
        $isEditingHimself = auth()->user()->id === (int) $request['id'];

        if (!$isSuperAdmin && !$isEditingHimself) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $hasImage = isset($request['image']) && $request->hasFile('image');

        $request_data = $hasImage ? Arr::except($request->validated(), ['image']) : $request->validated();

        // only super admin can manage users and rules
        $user = $this->userService->save($request_data, $isSuperAdmin);

        if ($hasImage) {
            $user->addMedia($request['image'])->toMediaCollection('profile_pics');
        }

        if ($user) {
            return response()->json($isEditingHimself ? new UserLoggedResource($user) : new UserResource($user));
        } else  return response()->json(['message' => 'User not found.'], 404);
    }

    public function destroy(String $id)
    {
        if (!auth()->user()->hasRole('admin')) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $this->userService->delete($id);
        return response()->json(null, 204);
    }

    public function getList()
    {
        $isSuperAdmin = auth()->user()->hasRole('super_admin');
        $isAdmin = auth()->user()->hasRole('admin');
        $isOperator = auth()->user()->hasRole('operator');

        if (!$isSuperAdmin && !$isAdmin && !$isOperator) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $users = $this->userService->getAll();
        return response()->json(UsersList::collection($users), 200);
    }    
}
