<?php

use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\Access\AccessServicesFactory;

ApiBootstrap::init();
ApiResponse::requireMethod('GET');
ApiResponse::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_PERMISSIONS_VIEW);
$request = requestInput();

$permissionService = (app(AccessServicesFactory::class))->createPermissionService();

$allowedOrders = ['key', 'description', 'active', 'created'];
$orderParam = $request->queryString('order');
$dirParam = strtolower($request->queryString('dir'));
$order = in_array($orderParam, $allowedOrders, true) ? $orderParam : 'key';
$dir = in_array($dirParam, ['asc', 'desc'], true) ? $dirParam : 'asc';
$limit = max(1, min(100, $request->queryInt('limit', 25)));
$offset = max(0, $request->queryInt('offset', 0));

$options = [
    'limit' => $limit,
    'offset' => $offset,
    'search' => $request->queryString('search'),
    'active' => $request->query('active'),
    'order' => $order,
    'dir' => $dir,
];

$result = $permissionService->listPaged($options);

$rows = [];
foreach (($result['rows'] ?? []) as $row) {
    $rows[] = [
        'key' => $row['key'] ?? '',
        'description' => $row['description'] ?? '',
        'active' => (bool) ($row['active'] ?? 1),
        'is_system' => (bool) ($row['is_system'] ?? 0),
    ];
}

ApiResponse::success([
    'data' => $rows,
    'total' => $result['total'] ?? 0,
    'limit' => $limit,
    'offset' => $offset,
]);
