<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\PermissionResource;
use App\Models\Permission;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PermissionController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        try {
            $permissions = Permission::all()->groupBy('module');

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

    public function show(Permission $permission): JsonResponse
    {
        try {
            return response()->json([
                'success' => true,
                'data' => new PermissionResource($permission),
                'message' => 'اطلاعات دسترسی',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت اطلاعات دسترسی',
            ], 500);
        }
    }
}
