<?php

require_once __DIR__ . '/../../middleware/auth.php';
require_once __DIR__ . '/../Inbox/InboxService.php';
require_once __DIR__ . '/../../config/app.php';

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

global $pdo;
$config = require __DIR__ . '/../../config/app.php';
$user = requireAuth();
$inboxService = new InboxService($pdo, $config);
$primaryEmail = (string) ($user['email'] ?? '');
if ($primaryEmail === '' && !empty($user['username'])) {
    $primaryEmail = buildUserInboxEmail((string) $user['username'], $config);
}

$inbox = $inboxService->ensureUserInbox((int) $user['id'], $primaryEmail);
$repo = new InboxRepository($pdo);
$inboxes = $repo->listActiveInboxesForUser((int) $user['id']);

jsonResponse(true, 'Current user fetched successfully', [
    'user' => $user,
    'inbox' => [
        'id' => $inbox['id'] ?? null,
        'type' => $inbox['type'] ?? 'user',
        'email_address' => $inbox['email_address'] ?? $primaryEmail,
        'expires_at' => $inbox['expires_at'] ?? null,
    ],
    'inboxes' => $inboxes,
]);
