<?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::DEPARTMENTS_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()->createDepartmentService()->listPaged($options);

    $rows = [];
    foreach ($result['rows'] as $row) {
        $rows[] = [
            'uuid' => $row['uuid'] ?? '',
            'description' => $row['description'] ?? '',
            'code' => $row['code'] ?? '',
            'active' => (bool) ($row['active'] ?? 1),
            'tenant_labels' => $row['tenant_labels'] ?? [],
            '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::DEPARTMENTS_CREATE);

    $input = ApiResponse::readJsonBody();
    $scopedTenantId = ApiAuth::scopedTenantId();
    if ($scopedTenantId) {
        $postedTenantId = (int) ($input['tenant_id'] ?? 0);
        if ($postedTenantId > 0 && $postedTenantId !== $scopedTenantId) {
            ApiResponse::forbidden('tenant_scoped_token_forbidden');
        }
        $input['tenant_id'] = $scopedTenantId;
    }
    $result = directoryServicesFactory()->createDepartmentService()->createFromAdmin($input, ApiAuth::userId());
    ApiResponse::fromServiceResult($result, 201);
}

ApiResponse::methodNotAllowed();
