<?php

declare(strict_types=1);

namespace App\Domain\Shared\Infrastructure\Service;

use App\Domain\Shared\Domain\Contract\FileUploadInterface;
use App\Domain\Shared\Domain\Exception\FileProcessingException;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\Exception\FileException;

readonly class SymfonyFileUpload implements FileUploadInterface
{
    public function __construct(
        private Filesystem $filesystem,
        private string $uploadsDirectory
    ) {
    }

    public function moveUploadedFile(string $sourcePath, string $targetDirectory, string $originalName): string
    {
        try {
            $targetPath = $targetDirectory . '/' . uniqid() . '_' . $originalName;
            $this->filesystem->copy($sourcePath, $targetPath);

            return $targetPath;
        } catch (FileException $e) {
            throw FileProcessingException::uploadFailed($originalName, $e->getMessage());
        }
    }

    public function fileExists(string $filePath): bool
    {
        return $this->filesystem->exists($filePath);
    }

    public function deleteFile(string $filePath): void
    {
        if ($this->filesystem->exists($filePath)) {
            $this->filesystem->remove($filePath);
        }
    }

    public function moveFile(string $sourcePath, string $targetPath): void
    {
        try {
            $this->filesystem->rename($sourcePath, $targetPath, true);
        } catch (FileException $e) {
            throw FileProcessingException::uploadFailed(
                basename($sourcePath),
                $e->getMessage()
            );
        }
    }

    public function createDirectory(string $path): void
    {
        if (!$this->filesystem->exists($path)) {
            $this->filesystem->mkdir($path, 0755);
        }
    }

    public function validateFileFormat(string $filePath, array $allowedExtensions): bool
    {
        $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
        return in_array($extension, $allowedExtensions, true);
    }
}
