<?php declare(strict_types=1);


namespace App\Controller\File;

use App\Repository\FileRepository;
use App\Service\SizeFormatter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class FileController extends AbstractController
{
    public function __construct(private readonly FileRepository $fileRepository)
    {
    }

    #[Route('/file/{filename}', name: 'app_serve_file')]
    public function serveFile(string $filename, SizeFormatter $sizeFormatter): Response
    {
        $file = $this->fileRepository->findOneBy(['name' => $filename]);

        if (!$file) {
            return new JsonResponse(['error' => 'File not found'], Response::HTTP_NOT_FOUND);
        }

        $filePath = $this->getParameter('kernel.project_dir')
            . '/public/uploads/' . $file->getUser()->getId() . '/' . $file->getName();

        if (!file_exists($filePath) || getimagesize($filePath) === false) {
            return new JsonResponse(['error' => 'Invalid file type'], Response::HTTP_BAD_REQUEST);
        }

        $fileSize = $sizeFormatter->formatSize($file->getSize());

        return $this->render('file_upload/index.html.twig', ['file' => $file]);
    }

    #[Route('/file/{filename}/delete', name: 'app_delete_file')]
    public function deleteFile(string $filename): JsonResponse|RedirectResponse
    {
        $user = $this->getUser();
        if (!$user) {
            return new JsonResponse(['error' => 'Invalid credentials, log in first'], Response::HTTP_FORBIDDEN);
        }

        $file = $this->fileRepository->findOneBy(['name' => $filename]);

        if (!$file) {
            return new JsonResponse(['error' => 'File not found'], Response::HTTP_NOT_FOUND);
        }

        if ($file->getUser()->getUsername() !== $user->getUserIdentifier()) {
            return new JsonResponse(['error' => 'Invalid credentials, log in first'], Response::HTTP_FORBIDDEN);
        }

        $filePath = $this->getParameter('kernel.project_dir')
            . '/public/uploads/' . $file->getUser()->getId() . '/' . $file->getName();

        // Delete file from disk and database
        unlink($filePath);
        $this->fileRepository->deleteFile($file);

        if (isset($_GET['redirectToHome'])) {
            return $this->redirectToRoute('app_home');
        }

        return new JsonResponse(['success' => 'File deleted'], Response::HTTP_OK);
    }

    #[Route('/file/{filename}/thumbnail', name: 'app_thumbnail_file')]
    public function showFileThumbnail(string $filename): RedirectResponse|JsonResponse
    {
        $file = $this->fileRepository->findOneBy(['name' => $filename]);

        if (!$file) {
            return new JsonResponse(['error' => 'File not found'], Response::HTTP_NOT_FOUND);
        }

        $filePath = '/uploads/' . $file->getUser()->getId() . '/' . $file->getName();

        return new RedirectResponse($filePath);
    }
}
