<?php

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

ApiBootstrap::init();

$uuid = trim((string) ($id ?? ''));
if ($uuid === '') {
    ApiResponse::notFound();
}

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

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

    $role = directoryServicesFactory()->createRoleService()->findByUuid($uuid);
    if (!$role) {
        ApiResponse::notFound();
    }

    ApiResponse::success([
        'data' => [
            'uuid' => $role['uuid'] ?? '',
            'description' => $role['description'] ?? '',
            'code' => $role['code'] ?? '',
            'active' => (bool) ($role['active'] ?? 1),
            'created' => $role['created'] ?? '',
            'modified' => $role['modified'] ?? '',
        ],
    ]);
}

if ($method === 'PUT' || $method === 'PATCH') {
    ApiResponse::requirePermission(PermissionService::ROLES_UPDATE);

    $role = directoryServicesFactory()->createRoleService()->findByUuid($uuid);
    if (!$role) {
        ApiResponse::notFound();
    }

    $roleId = (int) ($role['id'] ?? 0);
    $input = ApiResponse::readJsonBody();
    $result = directoryServicesFactory()->createRoleService()->updateFromAdmin($roleId, $input, ApiAuth::userId());
    ApiResponse::fromServiceResult($result);
}

if ($method === 'DELETE') {
    ApiResponse::requirePermission(PermissionService::ROLES_DELETE);

    $result = directoryServicesFactory()->createRoleService()->deleteByUuid($uuid);
    ApiResponse::fromServiceResult($result);
}

ApiResponse::methodNotAllowed();
