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

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

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

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

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

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

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

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

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

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

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

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

ApiResponse::methodNotAllowed();
