<?php

namespace App\Domain\Scraping\Infrastructure\Service;

use App\Domain\Scraping\Domain\Contract\Service\ImageStorageInterface;

readonly class LocalImageStorage implements ImageStorageInterface
{
    public function __construct(private string $storagePath)
    {
    }

    public function storeChapterImages(string $chapterId, array $localImagePaths): string
    {
        $targetDir = $this->storagePath . '/pages/' . $chapterId;

        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0755, true);
        }

        sort($localImagePaths);

        foreach ($localImagePaths as $index => $localPath) {
            $extension = pathinfo($localPath, PATHINFO_EXTENSION) ?: 'jpg';
            $targetFile = sprintf('%s/%03d.%s', $targetDir, $index + 1, $extension);
            copy($localPath, $targetFile);
        }

        return $targetDir;
    }
}
