<?php declare(strict_types=1);

namespace App\Engine\Files\FilesJs\Controllers;

final class ViewFileController extends BaseFileManagerController
{

    public function index(\Symfony\Component\HttpFoundation\Request $request): \Symfony\Component\HttpFoundation\Response
    {
        $url = $request->query->get('url', '');
        if (!$url || !filter_var($url, FILTER_VALIDATE_URL)) {
            return new \Symfony\Component\HttpFoundation\Response('Bad Request', 400);
        }

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_NOBODY, false);

        $response = curl_exec($ch);
        if ($response === false) {
            return new \Symfony\Component\HttpFoundation\Response('Failed to fetch file', 500);
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        if ($httpCode !== 200) {
            return new \Symfony\Component\HttpFoundation\Response('File not found', $httpCode);
        }

        $symfonyResponse = new \Symfony\Component\HttpFoundation\Response($response, 200);
        $symfonyResponse->headers->set('Content-Type', $contentType);

        return $symfonyResponse;
    }

}