<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreRoleRequest;
use App\Http\Requests\UpdateRoleRequest;
use App\Http\Resources\PermissionResource;
use App\Http\Resources\RoleResource;
use App\Models\Role;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        try {
            $query = Role::with('permissions')->withCount('users');

            $perPage = min((int) $request->input('per_page', 15), 100);
            $sortBy = in_array($request->input('sort_by'), ['id', 'name', 'display_name', 'created_at', 'updated_at'], true)
                ? $request->input('sort_by')
                : 'created_at';
            $sortDir = $request->input('sort_dir') === 'asc' ? 'asc' : 'desc';
            $roles = $query->orderBy($sortBy, $sortDir)->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => RoleResource::collection($roles),
                'meta' => [
                    'current_page' => $roles->currentPage(),
                    'last_page' => $roles->lastPage(),
                    'per_page' => $roles->perPage(),
                    'total' => $roles->total(),
                ],
                'message' => 'لیست نقش‌ها',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت نقش‌ها',
            ], 500);
        }
    }

    public function show(Role $role): JsonResponse
    {
        try {
            $role->load('permissions');

            return response()->json([
                'success' => true,
                'data' => new RoleResource($role),
                'message' => 'اطلاعات نقش',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت اطلاعات نقش',
            ], 500);
        }
    }

    public function store(StoreRoleRequest $request): JsonResponse
    {
        try {
            $data = $request->validated();
            $permissionIds = $data['permissions'] ?? [];
            unset($data['permissions']);

            $data['guard_name'] = $data['guard_name'] ?? 'web';

            $role = Role::create($data);
            $role->permissions()->sync($permissionIds);
            $role->load('permissions')->loadCount('users');

            return response()->json([
                'success' => true,
                'data' => new RoleResource($role),
                'message' => 'نقش با موفقیت ایجاد شد',
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در ایجاد نقش',
            ], 500);
        }
    }

    public function update(UpdateRoleRequest $request, Role $role): JsonResponse
    {
        try {
            $data = $request->validated();
            $permissionIds = $data['permissions'] ?? null;
            unset($data['permissions']);

            if (array_key_exists('guard_name', $data) && ! $data['guard_name']) {
                $data['guard_name'] = 'web';
            }

            $role->update($data);
            if ($permissionIds !== null) {
                $role->permissions()->sync($permissionIds);
            }
            $role->load('permissions')->loadCount('users');

            return response()->json([
                'success' => true,
                'data' => new RoleResource($role),
                'message' => 'نقش به‌روزرسانی شد',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در به‌روزرسانی نقش',
            ], 500);
        }
    }

    public function destroy(Role $role): JsonResponse
    {
        try {
            $role->delete();

            return response()->json([
                'success' => true,
                'message' => 'نقش حذف شد',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در حذف نقش',
            ], 500);
        }
    }

    public function assignPermissions(Request $request, Role $role): JsonResponse
    {
        try {
            $request->validate([
                'permissions' => 'present|array',
                'permissions.*' => 'exists:permissions,id',
            ]);

            $role->permissions()->sync($request->permissions);
            $role->load('permissions')->loadCount('users');

            return response()->json([
                'success' => true,
                'data' => new RoleResource($role),
                'message' => 'دسترسی‌های نقش به‌روزرسانی شد',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در به‌روزرسانی دسترسی‌های نقش',
            ], 500);
        }
    }

    public function getPermissions(Role $role): JsonResponse
    {
        try {
            $role->load('permissions');

            return response()->json([
                'success' => true,
                'data' => PermissionResource::collection($role->permissions),
                'message' => 'دسترسی‌های نقش',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت دسترسی‌های نقش',
            ], 500);
        }
    }
}
