<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\User\StoreUserRequest;
use App\Http\Requests\User\UpdateUserRequest;
use App\Http\Resources\UserResource;
use App\Services\UserService;
use Illuminate\Http\Request;

class UserController extends Controller
{
    protected $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function index(Request $request)
    {
        $result = $this->userService->index($request->all());

        if (isset($result['code']) && $result['code'] !== 0) {
            return response()->json($result);
        }

        $result['data']['items'] = UserResource::collection($result['data']['items']);

        return response()->json($result);
    }

    public function store(StoreUserRequest $request)
    {
        $result = $this->userService->store($request->validated());

        if (isset($result['code']) && $result['code'] !== 0) {
            return response()->json($result);
        }

        $result['data'] = new UserResource($result['data']);

        return response()->json($result);
    }

    public function show($id)
    {
        $result = $this->userService->show($id);

        if (isset($result['code']) && $result['code'] !== 0) {
            return response()->json($result);
        }

        $result['data'] = new UserResource($result['data']);

        return response()->json($result);
    }

    public function update(UpdateUserRequest $request, $id)
    {
        $result = $this->userService->update($id, $request->validated());

        if (isset($result['code']) && $result['code'] !== 0) {
            return response()->json($result);
        }

        $result['data'] = new UserResource($result['data']);

        return response()->json($result);
    }

    public function destroy($id)
    {
        $result = $this->userService->destroy($id);

        return response()->json($result);
    }

    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:0,1',
        ]);

        $result = $this->userService->updateStatus($id, $request->status);

        return response()->json($result);
    }

    public function resetPassword(Request $request, $id)
    {
        $request->validate([
            'password' => 'required|string|min:6|max:20',
        ]);

        $result = $this->userService->resetPassword($id, $request->password);

        return response()->json($result);
    }

    public function all()
    {
        $result = $this->userService->all();

        return response()->json($result);
    }

    public function batchDelete(Request $request)
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer',
        ]);

        $result = $this->userService->batchDelete($request->ids);

        return response()->json($result);
    }
}
