<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Log as LogModel;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use App\Http\Resources\UsersResource;
use Illuminate\Validation\Rule;

class UsersController extends Controller
{
    public function __construct(Request $request)
    {
        $this->log = new LogModel([
            'module' => 'user',
            'action' => $request->getMethod(),
            'target_type' => 'user',
        ]);
    }

    public function index()
    {
        $users = User::query()->where('id', '<>', 1)->with('roles:id,name,guard_name')->paginate();

        return UsersResource::collection($users);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:191|unique:users,name',
            'password' => 'required|string|min:8|confirmed',
            'email' => 'email',
            'role_name' => 'required|string|exists:roles,name'
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $user = new User();
        $user->name = $request->name;
        $user->password = $request->password;
        $user->api_token = Str::random(60);
        $user->save();
        $this->setAfterUpdate($user->toArray());
        $this->addLog($user->id, 'add');
        $user->assignRole($request->role_name);

        return new UsersResource($user);
    }

    public function show($id)
    {
        return new UsersResource(User::query()->with('roles:id,name,guard_name')->find($id));
    }

    public function update($id, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => [
                'required',
                'string',
                'max:191',
                Rule::unique('users')->ignore($id),
            ],
//            'old_password' => 'sometimes|required|string|min:8',
            'password' => 'sometimes|string|min:8|confirmed',
            'email' => 'sometimes|email',
            'role_name' => 'sometimes|required|string|exists:roles,name'
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $user = User::query()->find($id);
        $user->update($request->toArray());
        if ($request->has('role_name')) {
            $user->syncRoles($request->role_name);
        }

        return new UsersResource($user);
    }

    public function destory($id)
    {
        $user = User::query()->find($id);
        try {
            $user->delete();
            $this->addLog($id, 'status');
        } catch (\Exception $e) {
            $this->res = [
                'httpCode' => 500,
                'errorCode' => 500416,
                'errorMessage' => $e->getMessage(),
            ];
        }

        return response($this->res, $this->res['httpCode']);
    }
}
