<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\User\UserServicesFactory;

ApiBootstrap::init();
$userServicesFactory = new UserServicesFactory();
$userAccountService = $userServicesFactory->createUserAccountService();

$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

if ($method === 'GET') {
    ApiResponse::requirePermission(PermissionService::USERS_VIEW);

    $limit = max(1, min(100, (int) ($_GET['limit'] ?? 25)));
    $offset = max(0, (int) ($_GET['offset'] ?? 0));
    $allowedOrders = ['id', 'uuid', 'first_name', 'last_name', 'display_name', 'email', 'created', 'modified', 'active', 'last_login_at'];
    $order = in_array($_GET['order'] ?? '', $allowedOrders, true) ? $_GET['order'] : 'last_name';
    $dir = in_array(strtolower($_GET['dir'] ?? ''), ['asc', 'desc'], true) ? strtolower($_GET['dir']) : 'asc';
    $activeParam = $_GET['active'] ?? null;
    if ($activeParam !== null) {
        $activeParam = in_array($activeParam, ['0', '1', 'true', 'false'], true) ? $activeParam : null;
    }
    $options = [
        'limit' => $limit,
        'offset' => $offset,
        'search' => trim((string) ($_GET['search'] ?? '')),
        'order' => $order,
        'dir' => $dir,
        'active' => $activeParam,
        'tenantUserId' => ApiAuth::userId(),
    ];
    $scopedTenantId = ApiAuth::scopedTenantId();
    if ($scopedTenantId) {
        $tenant = directoryServicesFactory()->createTenantService()->findById($scopedTenantId);
        $tenantUuid = trim((string) ($tenant['uuid'] ?? ''));
        if ($tenantUuid === '') {
            ApiResponse::notFound();
        }
        $options['tenant'] = $tenantUuid;
    }
    $result = $userAccountService->listPaged($options);

    $rows = [];
    foreach ($result['rows'] as $row) {
        $rows[] = [
            'uuid' => $row['uuid'] ?? '',
            'first_name' => $row['first_name'] ?? '',
            'last_name' => $row['last_name'] ?? '',
            'display_name' => $row['display_name'] ?? '',
            'email' => $row['email'] ?? '',
            'job_title' => $row['job_title'] ?? '',
            'phone' => $row['phone'] ?? '',
            'mobile' => $row['mobile'] ?? '',
            'active' => (bool) ($row['active'] ?? 1),
            'created' => $row['created'] ?? '',
            'tenants' => $row['tenant_labels'] ?? [],
            'departments' => $row['department_labels'] ?? [],
            'roles' => $row['role_labels'] ?? [],
        ];
    }

    ApiResponse::success([
        'data' => $rows,
        'total' => $result['total'] ?? 0,
        'limit' => $limit,
        'offset' => $offset,
    ]);
}

if ($method === 'POST') {
    ApiResponse::requirePermission(PermissionService::USERS_CREATE);

    $input = ApiResponse::readJsonBody();
    $scopedTenantId = ApiAuth::scopedTenantId();
    if ($scopedTenantId) {
        $tenantIdsRaw = $input['tenant_ids'] ?? [];
        if (!is_array($tenantIdsRaw)) {
            $tenantIdsRaw = [$tenantIdsRaw];
        }
        $tenantIds = array_values(array_unique(array_filter(array_map(
            static fn ($value): int => (int) $value,
            $tenantIdsRaw
        ), static fn (int $value): bool => $value > 0)));
        if ($tenantIds && array_diff($tenantIds, [$scopedTenantId])) {
            ApiResponse::forbidden('tenant_scoped_token_forbidden');
        }

        $primaryTenantId = (int) ($input['primary_tenant_id'] ?? 0);
        if ($primaryTenantId > 0 && $primaryTenantId !== $scopedTenantId) {
            ApiResponse::forbidden('tenant_scoped_token_forbidden');
        }

        $input['tenant_ids'] = [$scopedTenantId];
        $input['primary_tenant_id'] = $scopedTenantId;
    }
    $result = $userAccountService->createFromAdmin($input, ApiAuth::userId());
    ApiResponse::fromServiceResult($result, 201);
}

ApiResponse::methodNotAllowed();
