<?php

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

requireAdmin();

if (getMethod() !== 'GET') {
    jsonResponse(false, 'method.not_allowed', null, 405);
}

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;
}

$route = getApiRouteSegments();
$mailboxId = isset($route[2]) && ctype_digit((string) $route[2]) ? (int) $route[2] : 0;

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

global $pdo;
$repo = new MailboxRepository($pdo);

if ($mailboxId <= 0) {
    jsonResponse(false, 'mailboxes.not_found', ['route' => $route], 404);
}

$mailbox = $repo->findById($mailboxId);
if (!$mailbox) {
    jsonResponse(false, 'mailboxes.not_found', ['mailbox_id' => $mailboxId], 404);
}

$result = $repo->getMessagesByMailboxIdPaginated($mailboxId, $page, $limit);
respondPaginated('mailboxes.messages_list_success', $result['items'], $result['pagination']);
