<?php

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

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

global $pdo;
$config = require __DIR__ . '/../../config/app.php';

$input = getMethod() === 'POST' ? getJsonInput() : [];
$rawUsername = trim((string) ($_GET['username'] ?? $input['username'] ?? ''));
$username = normalizeUsername($rawUsername);
$email = $username !== '' ? buildUserInboxEmail($username, $config) : '';

if ($username === '') {
    jsonResponse(false, 'username_required', [
        'available' => false,
        'username' => '',
        'email' => '',
    ], 422);
}

if (strlen($username) < 4) {
    jsonResponse(true, 'username_too_short', [
        'available' => false,
        'username' => $username,
        'email' => $email,
        'reason' => 'too_short',
    ]);
}

if (!isValidInboxUsername($username)) {
    jsonResponse(true, 'invalid_username', [
        'available' => false,
        'username' => $username,
        'email' => $email,
        'reason' => 'invalid_format',
        'rules' => 'Username must use letters, numbers, dot, dash, or underscore.',
    ]);
}

$reserved = array_map('strtolower', $config['guest_inbox']['reserved_usernames'] ?? [
    'admin',
    'administrator',
    'support',
    'mail',
    'mailer',
    'postmaster',
    'abuse',
    'security',
    'help',
    'info',
    'contact',
    'test',
]);

if (in_array($username, $reserved, true)) {
    jsonResponse(true, 'username_reserved', [
        'available' => false,
        'username' => $username,
        'email' => $email,
        'reason' => 'reserved',
    ]);
}

$userCheck = $pdo->prepare('SELECT id FROM users WHERE username = :username OR email = :email LIMIT 1');
$userCheck->execute([
    'username' => $username,
    'email' => $email,
]);

if ($userCheck->fetch()) {
    jsonResponse(true, 'username_exists', [
        'available' => false,
        'username' => $username,
        'email' => $email,
        'reason' => 'user_exists',
    ]);
}

$inboxCheck = $pdo->prepare('SELECT id FROM inboxes WHERE LOWER(email_address) = LOWER(:email_address) LIMIT 1');
$inboxCheck->execute(['email_address' => $email]);

if ($inboxCheck->fetch()) {
    jsonResponse(true, 'inbox_email_exists', [
        'available' => false,
        'username' => $username,
        'email' => $email,
        'reason' => 'inbox_exists',
    ]);
}

jsonResponse(true, 'username_available', [
    'available' => true,
    'username' => $username,
    'email' => $email,
]);
