<?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_DEPARTMENTS_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)->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' => $limit,
        'offset' => $offset,
    ]);
}

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

    $input = $request->bodyAll();
    if (array_key_exists('tenant_id', $input)) {
        ApiResponse::validationFromFormErrors(formErrorsFrom(['tenant_id' => ['use_tenant_uuid']]));
    }
    if (array_key_exists('tenant_uuid', $input)) {
        $tenantUuid = trim((string) ($input['tenant_uuid'] ?? ''));
        if ($tenantUuid !== '') {
            $tenant = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createTenantService()->findByUuid($tenantUuid);
            if (!$tenant) {
                ApiResponse::validationFromFormErrors(formErrorsFrom(['tenant_uuid' => ['not_found']]));
            }
            $input['tenant_id'] = (int) ($tenant['id'] ?? 0);
        }
        unset($input['tenant_uuid']);
    }
    $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 = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createDepartmentService()->createFromAdmin($input, ApiAuth::userId());
    ApiResponse::fromServiceResult($result, 201);
}

ApiResponse::methodNotAllowed();
