<?php

namespace App\Providers\ZipGenerator;

use App\Modules\Shared\Domain\ValueObject\Uuid;
use App\Providers\DirGenerator\DirGenerator;
use App\Providers\StorageProvider;
use ZipArchive;

class ZipGenerator
{
    public function __construct(
        private StorageProvider $storageProvider,
        private DirGenerator $dirGenerator
    ) {
    }

    public function generateFromFiles(array $files, ?string $filename = null, ?string $path = null): string
    {
        $zip = new ZipArchive();
        $privatePath = $this->storageProvider->privatePath('');
        $filename = $path ? $path : $this->generateZipFileName($filename, $privatePath);

        $zip->open($privatePath . $filename, \ZipArchive::CREATE);
        foreach ($files as $file) {
            $zip->addFile($file, pathinfo($file, PATHINFO_BASENAME));
        }
        $zip->close();

        return $filename;
    }

    public function generateZipFileName(?string $filename, $privatePath): string
    {
        $path = 'files' . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR;
        $prefix = 'zip';
        $directory = $this->dirGenerator->createDirectoryByMonth($privatePath, $path, $prefix) . DIRECTORY_SEPARATOR;
        $name = $filename ? $filename : Uuid::random()->value();
        return $directory . $name . '.zip';
    }
}
