<?php

require_once __DIR__ . '/../../../config/helpers.php';

$route = getApiRouteSegments();
$method = getMethod();

$section = strtolower((string) ($route[1] ?? ''));
$third = strtolower((string) ($route[2] ?? ''));
$fourth = strtolower((string) ($route[3] ?? ''));
$fifth = strtolower((string) ($route[4] ?? ''));
$sixth = strtolower((string) ($route[5] ?? ''));
$seventh = strtolower((string) ($route[6] ?? ''));

$id = ctype_digit($third) ? (int) $third : null;
$messageId = ctype_digit($fifth) ? (int) $fifth : null;
$attachmentId = ctype_digit($seventh) ? (int) $seventh : null;

if ($section !== 'mailboxes') {
    jsonResponse(false, 'mailboxes.route_not_found', [
        'method' => $method,
        'segments' => $route,
    ], 404);
}

if ($third === 'test-connection' && $method === 'POST') {
    require __DIR__ . '/test-connection.php';
    return;
}

if (!$id && $method === 'GET') {
    require __DIR__ . '/list.php';
    return;
}

if (!$id && $method === 'POST') {
    require __DIR__ . '/create.php';
    return;
}

if ($id && $fourth === 'sync' && $method === 'POST') {
    require __DIR__ . '/sync.php';
    return;
}

if ($id && $fourth === 'messages' && !$messageId && $method === 'GET') {
    require __DIR__ . '/messages.php';
    return;
}

if ($id && $fourth === 'messages' && $messageId && $sixth === 'attachments' && $method === 'GET') {
    require __DIR__ . '/attachments.php';
    return;
}

if ($id && $fourth === 'messages' && $messageId && $sixth === 'download' && $attachmentId && $method === 'GET') {
    require __DIR__ . '/attachment-download.php';
    return;
}

if ($id && $fourth === 'messages' && $messageId && $sixth === 'inline' && $attachmentId && $method === 'GET') {
    require __DIR__ . '/inline-file.php';
    return;
}

if ($id && $fourth === 'messages' && $messageId && $sixth === 'mark-read' && $method === 'POST') {
    require __DIR__ . '/mark-read.php';
    return;
}

if ($id && $fourth === 'messages' && $messageId && $sixth === 'mark-unread' && $method === 'POST') {
    require __DIR__ . '/mark-unread.php';
    return;
}



if ($id && $fourth === 'messages' && $messageId && $sixth === 'star' && $method === 'POST') {
    require __DIR__ . '/star.php';
    return;
}

if ($id && $fourth === 'messages' && $messageId && $sixth === 'unstar' && $method === 'POST') {
    require __DIR__ . '/unstar.php';
    return;
}

if ($id && $fourth === 'messages' && $messageId && $method === 'GET') {
    require __DIR__ . '/message-show.php';
    return;
}

if ($id && $method === 'GET') {
    require __DIR__ . '/show.php';
    return;
}

if ($id && in_array($method, ['PUT', 'PATCH'], true)) {
    require __DIR__ . '/update.php';
    return;
}

if ($id && $method === 'DELETE') {
    require __DIR__ . '/delete.php';
    return;
}

jsonResponse(false, 'mailboxes.route_not_found', [
    'method' => $method,
    'segments' => $route,
], 404);