<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;

ApiBootstrap::init();

$request = requestInput();
$method = $request->method();

if ($method === 'GET') {
    ApiResponse::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_ROLES_VIEW);

    $limit = $request->queryInt('limit', 25);
    $offset = $request->queryInt('offset', 0);
    $result = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createRoleService()->listPaged([
        'limit' => $limit,
        'offset' => $offset,
        'search' => $request->queryString('search'),
        'order' => $request->queryString('order', 'description'),
        'dir' => $request->queryString('dir', 'asc'),
    ]);

    $rows = [];
    foreach ($result['rows'] as $row) {
        $rows[] = [
            'uuid' => $row['uuid'] ?? '',
            'description' => $row['description'] ?? '',
            'code' => $row['code'] ?? '',
            'active' => (bool) ($row['active'] ?? 1),
            'created' => $row['created'] ?? '',
        ];
    }

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

if ($method === 'POST') {
    ApiResponse::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_ROLES_CREATE);

    $input = $request->bodyAll();
    $result = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createRoleService()->createFromAdmin($input, ApiAuth::userId());
    ApiResponse::fromServiceResult($result, 201);
}

ApiResponse::methodNotAllowed();
