<?php

namespace Inside\DESK\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inside\Content\Models\Contents\Jobs;
use Inside\Kernel\Filesystem\Facades\FileStreamer;
use Laravel\Lumen\Routing\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ExternalApiController extends Controller
{
    public function getResource(Request $request, string $path): Response | JsonResponse
    {
        preg_match('/\/file\/(\d{4}-\d{2}).*/', $path, $matches);
        $filePath = preg_replace('/\/file/', '', $matches[0]);
        $filePath = urldecode($filePath);
        if (! Storage::exists($filePath)) {
            return new JsonResponse(['message' => 'File not found !'], 404);
        }

        return $this->getFileFromStorage($filePath);
    }

    private function getFileFromStorage(string $filePath): StreamedResponse
    {
        return FileStreamer::streamFile($filePath);
    }
}
