<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\Access\PermissionService;

ApiBootstrap::init();

$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

if ($method === 'GET') {
    ApiResponse::requirePermission(PermissionService::ROLES_VIEW);

    $result = directoryServicesFactory()->createRoleService()->listPaged([
        'limit' => (int) ($_GET['limit'] ?? 25),
        'offset' => (int) ($_GET['offset'] ?? 0),
        'search' => trim((string) ($_GET['search'] ?? '')),
        'order' => (string) ($_GET['order'] ?? 'description'),
        'dir' => (string) ($_GET['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' => (int) ($_GET['limit'] ?? 25),
        'offset' => (int) ($_GET['offset'] ?? 0),
    ]);
}

if ($method === 'POST') {
    ApiResponse::requirePermission(PermissionService::ROLES_CREATE);

    $input = ApiResponse::readJsonBody();
    $result = directoryServicesFactory()->createRoleService()->createFromAdmin($input, ApiAuth::userId());
    ApiResponse::fromServiceResult($result, 201);
}

ApiResponse::methodNotAllowed();
