<?php
declare(strict_types=1);

namespace App\Modules\PublicArea;

use App\Core\Request;

final class MediaController
{
    public function show(Request $request): never
    {
        $path = trim((string) $request->input('path', ''));
        if ($path === '' || ! preg_match('/^[a-zA-Z0-9\/_.-]+$/', $path) || str_contains($path, '..')) {
            abort(404, 'File tidak ditemukan.');
        }

        $baseDirectory = realpath(dirname(__DIR__, 3) . '/storage/uploads');
        $targetPath = realpath(dirname(__DIR__, 3) . '/' . ltrim($path, '/'));

        if ($baseDirectory === false || $targetPath === false || ! str_starts_with($targetPath, $baseDirectory . DIRECTORY_SEPARATOR)) {
            abort(404, 'File tidak ditemukan.');
        }

        if (! is_file($targetPath)) {
            abort(404, 'File tidak ditemukan.');
        }

        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = $finfo !== false ? finfo_file($finfo, $targetPath) : null;
        if ($finfo !== false) {
            finfo_close($finfo);
        }

        if (! is_string($mimeType) || $mimeType === '') {
            $mimeType = 'application/octet-stream';
        }

        header('Content-Type: ' . $mimeType);
        header('Content-Length: ' . filesize($targetPath));
        header('Cache-Control: public, max-age=86400');
        readfile($targetPath);
        exit;
    }
}
