<?php

use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_VIEW, [
    'actor_user_id' => (int) ($session['user']['id'] ?? 0),
]);
if (!$decision->isAllowed()) {
    if (Request::wantsJson()) {
        http_response_code($decision->status());
        Router::json(['error' => $decision->error()]);
        return;
    }
    Router::redirect('error/forbidden?url=' . urlencode(Request::pathWithQuery()));
    return;
}
$userAccountService = app(\MintyPHP\Service\User\UserAccountService::class);

$currentUserId = (int) ($session['user']['id'] ?? 0);

$search = trim((string) (requestInput()->queryAll()['search'] ?? ''));
$order = (string) (requestInput()->queryAll()['order'] ?? 'id');
$dir = strtolower((string) (requestInput()->queryAll()['dir'] ?? 'desc')) === 'asc' ? 'asc' : 'desc';
$active = requestInput()->queryAll()['active'] ?? 'all';
$createdFrom = trim((string) (requestInput()->queryAll()['created_from'] ?? ''));
$createdTo = trim((string) (requestInput()->queryAll()['created_to'] ?? ''));
$tenant = trim((string) (requestInput()->queryAll()['tenant'] ?? ''));
$roles = requestInput()->queryAll()['roles'] ?? '';
$departments = requestInput()->queryAll()['departments'] ?? '';

$allowedOrder = ['id', 'uuid', 'first_name', 'last_name', 'email', 'locale', 'theme', 'created', 'modified', 'active'];
if (!in_array($order, $allowedOrder, true)) {
    $order = 'id';
}

$limit = (int) (requestInput()->queryAll()['limit'] ?? 5000);
if ($limit < 1) {
    $limit = 5000;
}
if ($limit > 5000) {
    $limit = 5000;
}

$result = $userAccountService->listPaged([
    'limit' => $limit,
    'offset' => 0,
    'search' => $search,
    'order' => $order,
    'dir' => $dir,
    'active' => $active,
    'created_from' => $createdFrom,
    'created_to' => $createdTo,
    'tenant' => $tenant,
    'roles' => $roles,
    'departments' => $departments,
    'tenantUserId' => $currentUserId,
]);

$exportRows = $result['rows'] ?? [];
$exportFilename = 'users-' . date('Ymd-His') . '.csv';
