<?php

declare(strict_types=1);


namespace App\Blog\Controllers;

use App\Blog\Support\ThemeManager;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\File;

class ThemeAssetController extends Controller
{
    public function show(ThemeManager $themes, string $theme, string $path)
    {
        if (! $themes->exists($theme)) {
            abort(404);
        }

        $fullPath = $themes->path($theme).'/assets/'.$path;
        if (! File::isFile($fullPath)) {
            abort(404);
        }

        return response(File::get($fullPath), 200, [
            'Content-Type' => $this->mimeType($fullPath),
            'Cache-Control' => 'public, max-age=86400',
        ]);
    }

    private function mimeType(string $path): string
    {
        $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));

        return match ($ext) {
            'css' => 'text/css',
            'js' => 'application/javascript',
            'png' => 'image/png',
            'jpg', 'jpeg' => 'image/jpeg',
            'gif' => 'image/gif',
            'svg' => 'image/svg+xml',
            'woff' => 'font/woff',
            'woff2' => 'font/woff2',
            'ico' => 'image/x-icon',
            default => 'application/octet-stream',
        };
    }
}
