<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;

ApiBootstrap::init();
$request = requestInput();

$uuid = trim((string) ($id ?? ''));
if ($uuid === '') {
    ApiResponse::notFound();
}

$method = $request->method();

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

    $department = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createDepartmentService()->findByUuid($uuid);
    if (!$department) {
        ApiResponse::notFound();
    }

    $departmentId = (int) ($department['id'] ?? 0);
    ApiAuth::requireResourceAccess('departments', $departmentId);
    $tenantUuid = '';
    $tenantId = (int) ($department['tenant_id'] ?? 0);
    if ($tenantId > 0) {
        $tenant = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createTenantService()->findById($tenantId);
        $tenantUuid = (string) ($tenant['uuid'] ?? '');
    }

    ApiResponse::success([
        'data' => [
            'uuid' => $department['uuid'] ?? '',
            'description' => $department['description'] ?? '',
            'code' => $department['code'] ?? '',
            'cost_center' => $department['cost_center'] ?? '',
            'active' => (bool) ($department['active'] ?? 1),
            'tenant_uuid' => $tenantUuid,
            'created' => $department['created'] ?? '',
            'modified' => $department['modified'] ?? '',
        ],
    ]);
}

if ($method === 'PUT' || $method === 'PATCH') {
    ApiResponse::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_DEPARTMENTS_UPDATE);

    $department = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createDepartmentService()->findByUuid($uuid);
    if (!$department) {
        ApiResponse::notFound();
    }

    $departmentId = (int) ($department['id'] ?? 0);
    ApiAuth::requireResourceAccess('departments', $departmentId);

    $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);
        } else {
            $input['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()->updateFromAdmin($departmentId, $input, ApiAuth::userId());
    ApiResponse::fromServiceResult($result);
}

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

    $department = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createDepartmentService()->findByUuid($uuid);
    if (!$department) {
        ApiResponse::notFound();
    }

    $departmentId = (int) ($department['id'] ?? 0);
    ApiAuth::requireResourceAccess('departments', $departmentId);

    $result = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createDepartmentService()->deleteByUuid($uuid);
    ApiResponse::fromServiceResult($result);
}

ApiResponse::methodNotAllowed();
