<?php

namespace App\Http\Controllers\Admin;

use App\Facades\DataTable\DataTableFacade;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\RoleManagement\StoreRequest;
use App\Http\Requests\Admin\RoleManagement\UpdateRequest;
use App\Http\Resources\Admin\RoleResource;
use app\Http\Traits\ApiResponse;
use App\Models\Role;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RoleManagementController extends Controller
{
    use ApiResponse;
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        $data = DataTableFacade::run(
            Role::query(),
            $request,
            allowedFilters: array('id', 'name', 'name_fa'),
            allowedSortings: array('id', 'name', 'name_fa'),
            allowedRelations: array('permissions:id,name_fa')
        );

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreRequest $request): JsonResponse
    {
        DB::transaction(function () use ($request) {
            $role = Role::create([
                'name' => $request->name,
                'name_fa' => $request->name_fa,
                'guard_name' => 'web'
            ]);

            $role->syncPermissions($request->permissions);
        });

        return $this->successResponse();
    }

    /**
     * Display the specified resource.
     */
    public function show(Role $role): JsonResponse
    {
        return $this->successResponse(new RoleResource($role));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateRequest $request, Role $role): JsonResponse
    {
        DB::transaction(function () use ($request, $role) {
            $role->update([
                'name' => $request->name,
                'name_fa' => $request->name_fa,
                'guard_name' => 'web'
            ]);

            $role->syncPermissions($request->permissions);
        });

        return $this->successResponse();
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Role $role): JsonResponse
    {
        DB::transaction(function () use ($role) {
            $role->syncPermissions([]);

            $role->delete();
        });

        return $this->successResponse();
    }

    public function list(): JsonResponse
    {
        return $this->successResponse(RoleResource::collection(Role::all()));
    }
}
