<?php

namespace App\Service;

use App\Entity\Image;
use App\Repository\NewsImageRepository;
use League\Flysystem\FilesystemOperator;

class ImageService
{
    public function __construct(
        private FilesystemOperator $minioStorage,
        private NewsImageRepository $newsImageRepository
    ) {}

    public function upload(string $path, $content): bool
    {
        try {
            if (is_resource($content)) {
                $this->minioStorage->writeStream($path, $content);
                fclose($content);
            } else {
                $this->minioStorage->write($path, $content);
            }

            return true;
        } catch (\Throwable $e) {
            $this->logger->error('Image upload failed: ' . $e->getMessage());
            return false;
        }
    }

    public function delete(Image $image): bool
    {
        $isUsed = $this->checkIfUsed($image);
        if ($isUsed) {
            return false;
        } else {
            try {
                $this->minioStorage->delete($image->getName());

                return true;
            } catch (\Throwable $e) {

                $this->logger->error('File deletion failed: ' . $e->getMessage());
                return false;
            }
        }
    }

    private function checkIfUsed(Image $image): bool
    {
        return (bool) $this->newsImageRepository->findOneBy(['image' => $image]);
    }
}
