<?php

namespace Shopping\Feed;

class FeedNamer {

    public function __construct(private string $baseDir) {
        if (!is_dir($this->baseDir)) {
            mkdir($this->baseDir, 0775, true);
        }
    }

    public function tempPath(int $publisherId): string {
        return "{$this->baseDir}/{$publisherId}.shopping.tmp";
    }

    public function finalPath(int $publisherId): string {
        $date = date('Ymd');
        return "{$this->baseDir}/{$publisherId}.shopping.{$date}.jsonl";
    }

    public function publish(int $publisherId): string {
        $final = $this->finalPath($publisherId);

        if (!rename($this->tempPath($publisherId), $final)) {
            throw new \RuntimeException("Failed to publish feed for {$publisherId}");
        }

        return $final;
    }
}