<?php

require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../config/helpers.php';
require_once __DIR__ . '/../../../middleware/admin.php';
require_once __DIR__ . '/MailboxRepository.php';

function respondPaginated(string $message, array $items, array $pagination, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');

    echo json_encode([
        'ok' => true,
        'message' => $message,
        'data' => $items,
        'pagination' => $pagination,
    ]);
    exit;
}

requireAdmin();
global $pdo;

$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;
$page = max(1, $page);
$limit = max(1, min($limit, 100));

$repo = new MailboxRepository($pdo);
$result = $repo->paginate($page, $limit);

respondPaginated('mailboxes.list_success', $result['items'], $result['pagination']);
