<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\Upload;

class FileAccess
{
    public function handle(Request $request, Closure $next): Response
    {
        $fileKey = $request->route('filekey');

        $filekeyArr = explode('.', $fileKey);
        $fileByKey = Upload::where('short_key', $filekeyArr[0])->first();
        $fileByName = Upload::where('filename', $fileKey)->first();

        if (!$fileByKey && !$fileByName) {
            return response()
                ->file(public_path('assets/image/file-deleted.webp'));
        }

        $fileData = $fileByKey ?: $fileByName;

        $allowedTypes = config('upload.DIRECT_ACCESS');
        $allowedTypesArr = explode(',', $allowedTypes);

        if ($allowedTypesArr) {
            if (in_array($fileData->filetype, $allowedTypesArr)) {
                return $next($request);
            }
            return abort(404);
        }

        return abort(404);
    }

}
