<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;

/**
 * UploadController
 *
 * /uploads sits outside the public web root on purpose (see
 * docs/ARCHITECTURE.md §6) — nothing in it is directly linkable. This
 * controller is the only sanctioned way to view an uploaded file, and
 * it exists specifically so path traversal ("../../.env") is
 * impossible: realpath() is checked against the uploads root before
 * anything is ever read from disk.
 */
final class UploadController extends BaseController
{
    public function show(Request $request, array $params): Response
    {
        $relativePath = $params['path'] ?? '';
        $uploadsRoot = realpath(dirname(__DIR__, 2) . '/uploads');
        $requested = realpath($uploadsRoot . '/' . $relativePath);

        if ($requested === false || !str_starts_with($requested, (string) $uploadsRoot) || !is_file($requested)) {
            return Response::html('404 Not Found', 404);
        }

        $mime = mime_content_type($requested) ?: 'application/octet-stream';
        $contents = file_get_contents($requested);

        return Response::html($contents === false ? '' : $contents)
            ->withHeader('Content-Type', $mime)
            ->withHeader('Cache-Control', 'private, max-age=86400');
    }
}
