<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Models\PermissionModel;
use App\Services\ActivityLogger;

final class PermissionController extends BaseController
{
    public function matrix(Request $request): Response
    {
        $matrix = (new PermissionModel())->matrix();

        return AjaxResponse::success($matrix);
    }

    /** Replaces one role's entire permission set — the "Save Changes" button on the Permission Matrix. */
    public function updateRolePermissions(Request $request, array $params): Response
    {
        $roleId = (int) $params['roleId'];
        $permissionIds = array_map('intval', (array) $request->input('permission_ids', []));

        (new PermissionModel())->syncRolePermissions($roleId, $permissionIds);

        ActivityLogger::record(
            'role',
            $roleId,
            'permissions_updated',
            'Updated permission grants for role',
            ['permission_count' => count($permissionIds)],
            category: 'admin'
        );

        return AjaxResponse::success(null, 'Permissions saved.');
    }
}
