<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Repository\Access\RolePermissionRepository;

ApiBootstrap::init();
$request = requestInput();

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

$method = $request->method();

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

    $role = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createRoleService()->findByUuid($uuid);
    if (!$role) {
        ApiResponse::notFound();
    }
    $roleId = (int) ($role['id'] ?? 0);
    $permissionKeys = [];
    if ($roleId > 0) {
        $permissionKeys = app(RolePermissionRepository::class)->listPermissionKeysByRoleIds([$roleId]);
        sort($permissionKeys);
    }

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

if ($method === 'PUT' || $method === 'PATCH') {
    ApiResponse::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_ROLES_UPDATE);

    $role = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createRoleService()->findByUuid($uuid);
    if (!$role) {
        ApiResponse::notFound();
    }

    $roleId = (int) ($role['id'] ?? 0);
    $input = $request->bodyAll();
    $result = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createRoleService()->updateFromAdmin($roleId, $input, ApiAuth::userId());
    ApiResponse::fromServiceResult($result);
}

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

    $result = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createRoleService()->deleteByUuid($uuid);
    ApiResponse::fromServiceResult($result);
}

ApiResponse::methodNotAllowed();
