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

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

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

if ($mailboxId <= 0 || !$repo->findById($mailboxId)) {
    jsonResponse(false, 'mailboxes.not_found', null, 404);
}

$message = $repo->getMessageById($mailboxId, $messageId);
if (!$message) {
    jsonResponse(false, 'mailboxes.message_not_found', null, 404);
}

$attachments = $repo->getMessageAttachmentsByMessageId($messageId);

jsonResponse(true, 'mailboxes.attachments_list_success', $attachments);