<?php

namespace App\Domain\Scraping\Domain\Model\ValueObject;

class TempDirectory
{
    private string $path;

    public function __construct()
    {
        $this->path = sys_get_temp_dir() . '/' . uniqid('manga_scraper_');
        if (!mkdir($this->path, 0755, true)) {
            throw new \RuntimeException('Failed to create temporary directory');
        }
    }

    public function getPath(): string
    {
        return $this->path;
    }

    public function cleanup(): void
    {
        if (!is_dir($this->path)) {
            return;
        }

        $files = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($this->path, \RecursiveDirectoryIterator::SKIP_DOTS),
            \RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $file) {
            if ($file->isDir()) {
                rmdir($file->getRealPath());
            } else {
                unlink($file->getRealPath());
            }
        }

        rmdir($this->path);
    }

    public function __destruct()
    {
        $this->cleanup();
    }
}
