<?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::TENANTS_VIEW);

    $options = [
        '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'),
        'tenantUserId' => ApiAuth::userId(),
    ];
    $scopedTenantId = ApiAuth::scopedTenantId();
    if ($scopedTenantId) {
        $options['tenantIds'] = [$scopedTenantId];
    }
    $result = directoryServicesFactory()->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' => (int) ($_GET['limit'] ?? 25),
        'offset' => (int) ($_GET['offset'] ?? 0),
    ]);
}

if ($method === 'POST') {
    ApiResponse::requirePermission(PermissionService::TENANTS_CREATE);
    if (ApiAuth::isTenantScopedToken()) {
        ApiResponse::forbidden('tenant_scoped_token_forbidden');
    }

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

ApiResponse::methodNotAllowed();
