<?php

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

handleCors();

if (getMethod() !== 'POST') {
    jsonResponse(false, 'Method not allowed', null, 405);
}

$config = require __DIR__ . '/../../config/app.php';
requireAuth();

if (!isset($_FILES['file']) || !is_array($_FILES['file'])) {
    jsonResponse(false, 'upload.file_required', null, 422);
}

$file = $_FILES['file'];
$error = (int) ($file['error'] ?? UPLOAD_ERR_NO_FILE);
if ($error !== UPLOAD_ERR_OK) {
    $message = match ($error) {
        UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => 'upload.file_too_large',
        UPLOAD_ERR_PARTIAL => 'upload.file_partial',
        UPLOAD_ERR_NO_FILE => 'upload.file_required',
        default => 'upload.failed',
    };
    jsonResponse(false, $message, null, 422);
}

$maxSize = (int) ($config['upload']['max_size_bytes'] ?? (5 * 1024 * 1024));
if ((int) ($file['size'] ?? 0) <= 0) {
    jsonResponse(false, 'upload.empty_file', null, 422);
}
if ((int) $file['size'] > $maxSize) {
    jsonResponse(false, 'upload.file_too_large', ['max_size_bytes' => $maxSize], 422);
}

$originalName = (string) ($file['name'] ?? '');
$extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
$allowedExtensions = $config['upload']['allowed_extensions'] ?? ['jpg', 'jpeg', 'png', 'webp', 'gif'];
if ($extension === '' || !in_array($extension, $allowedExtensions, true)) {
    jsonResponse(false, 'upload.invalid_extension', ['allowed_extensions' => array_values($allowedExtensions)], 422);
}

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = (string) $finfo->file($file['tmp_name']);
$allowedMimeTypes = $config['upload']['allowed_mime_types'] ?? ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
if ($mimeType === '' || !in_array($mimeType, $allowedMimeTypes, true)) {
    jsonResponse(false, 'upload.invalid_type', ['allowed_mime_types' => array_values($allowedMimeTypes)], 422);
}

$relativeDirectory = trim((string) ($config['upload']['avatar_directory'] ?? 'uploads/avatars'), '/');
$absoluteDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relativeDirectory);

try {
    ensureDirectory($absoluteDirectory);
} catch (Throwable $e) {
    jsonResponse(false, 'upload.directory_failed', null, 500);
}

$filename = date('YmdHis') . '_' . bin2hex(random_bytes(8)) . '.' . $extension;
$absolutePath = $absoluteDirectory . DIRECTORY_SEPARATOR . $filename;

if (!move_uploaded_file($file['tmp_name'], $absolutePath)) {
    jsonResponse(false, 'upload.move_failed', null, 500);
}


$appBasePath = '/v1';
$relativePath = $appBasePath . '/' . $relativeDirectory . '/' . $filename;
$url = rtrim($config['app']['url'], '/') . '/' . $relativeDirectory . '/' . $filename;

jsonResponse(true, 'upload.success', [
    'filename' => $filename,
    'original_name' => $originalName,
    'mime_type' => $mimeType,
    'size' => (int) $file['size'],
    'path' => $relativePath,
    'url' => $url,
]);
