<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Support\SectionAccessManager;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class SectionAccessController extends Controller
{
    public function update(Request $request, string $entity, SectionAccessManager $sectionAccessManager): RedirectResponse
    {
        abort_unless($sectionAccessManager->supports($entity), 404);
        abort_unless($sectionAccessManager->canManage($request->user(), $entity), 403);

        $validated = $request->validate([
            'user_id' => ['required', 'integer', 'exists:users,id'],
            'permissions' => ['nullable', 'array'],
            'permissions.read' => ['nullable', 'boolean'],
            'permissions.create' => ['nullable', 'boolean'],
            'permissions.update' => ['nullable', 'boolean'],
            'permissions.delete' => ['nullable', 'boolean'],
        ]);

        $target = User::query()->findOrFail((int) $validated['user_id']);
        $permissions = is_array($validated['permissions'] ?? null) ? $validated['permissions'] : [];

        $sectionAccessManager->applyPermissions($target, $entity, $permissions);

        return back()->with('success', __('Section permissions updated.'));
    }
}

