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

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

    $tenantId = (int) ($tenant['id'] ?? 0);
    ApiAuth::requireResourceAccess('tenants', $tenantId);

    ApiResponse::success([
        'data' => [
            'uuid' => $tenant['uuid'] ?? '',
            'description' => $tenant['description'] ?? '',
            'status' => $tenant['status'] ?? '',
            'address' => $tenant['address'] ?? '',
            'postal_code' => $tenant['postal_code'] ?? '',
            'city' => $tenant['city'] ?? '',
            'country' => $tenant['country'] ?? '',
            'phone' => $tenant['phone'] ?? '',
            'email' => $tenant['email'] ?? '',
            'website' => $tenant['website'] ?? '',
            'created' => $tenant['created'] ?? '',
            'modified' => $tenant['modified'] ?? '',
        ],
    ]);
}

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

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

    $tenantId = (int) ($tenant['id'] ?? 0);
    ApiAuth::requireResourceAccess('tenants', $tenantId);

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

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

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

    $tenantId = (int) ($tenant['id'] ?? 0);
    ApiAuth::requireResourceAccess('tenants', $tenantId);

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

ApiResponse::methodNotAllowed();
