<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Resources\UserResource;
use App\Models\User;
use App\Support\ApiResponse;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class UserController extends Controller
{
    public function index(Request $request, ?User $user = null)
    {
        $items = new User;

        if ($request->conditions) {
            $items = $items->where(json_decode($request->conditions, true));
        }

        if ($request->with) {
            $items = $items->with($request->with);
        }

        return $request->noPaginate ? $items->get() : $items->paginate();
    }

    public function edit(Request $request, User $routeUser)
    {
        Gate::authorize('update', $routeUser);
        try {
            DB::beginTransaction();
            $data = $request->all();

            if (isset($request->password)) {
                $data['password'] = Hash::make($request->password);
            }

            if ($request->hasFile('avatar')) {
                $storage = Storage::disk('public')->putFile('files', $request->avatar);
                $data['avatar'] = $storage;
            }
            $routeUser->update($data);

            if (isset($request->role)) {
                if (Auth::user()->hasRole('admin')) {
                    $routeUser->syncRoles($request->role);
                } else {
                    return ApiResponse::response(message: 'شما مجوز تغییر نقش را ندارید', status: 403);
                }
            } else {
                $routeUser->syncRoles('user');
            }

            DB::commit();
        } catch (Exception $exception) {
            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return UserResource::make($routeUser);
    }

    public function destroy(User $routeUser)
    {
        Gate::authorize('delete', $routeUser);

        return $routeUser->delete();
    }

    public function show(Request $request)
    {
        $user = Auth::guard('api')->user();

        return UserResource::make($user);
    }

    public function store(Request $request)
    {
        Gate::authorize('create', User::class);
        try {
            DB::beginTransaction();
            $item = new User;
            $data = $request->all();
            $user = $item->create($data);

            if (isset($request->role)) {
                $user->syncRoles($request->role);
            } else {
                $user->syncRoles('user');
            }

            DB::commit();
        } catch (Exception $exception) {
            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return $user;
    }
}
