<?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_TENANTS_VIEW);

    $limit = $request->queryInt('limit', 25);
    $offset = $request->queryInt('offset', 0);
    $options = [
        'limit' => $limit,
        'offset' => $offset,
        'search' => $request->queryString('search'),
        'order' => $request->queryString('order', 'description'),
        'dir' => $request->queryString('dir', 'asc'),
        'tenantUserId' => ApiAuth::userId(),
    ];
    $scopedTenantId = ApiAuth::scopedTenantId();
    if ($scopedTenantId) {
        $options['tenantIds'] = [$scopedTenantId];
    }
    $result = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createTenantService()->listPaged($options);

    $rows = [];
    foreach ($result['rows'] as $row) {
        $rows[] = [
            'uuid' => $row['uuid'] ?? '',
            'description' => $row['description'] ?? '',
            'status' => $row['status'] ?? '',
            'city' => $row['city'] ?? '',
            'country' => $row['country'] ?? '',
            '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_TENANTS_CREATE);
    if (ApiAuth::isTenantScopedToken()) {
        ApiResponse::forbidden('tenant_scoped_token_forbidden');
    }

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

ApiResponse::methodNotAllowed();
