"""Tests unitaires pour jobs/utils.py (fonctions sans sudo)."""
from unittest.mock import patch


class TestUniqueArchiveName:
    def test_sans_collision(self):
        from jobs.utils import unique_archive_name
        with patch("jobs.utils.sudo_exists", return_value=False):
            result = unique_archive_name("instance_app_20260511", "/backups")
        assert result == "instance_app_20260511"

    def test_une_collision(self):
        from jobs.utils import unique_archive_name
        calls = {"n": 0}

        def exists(path):
            calls["n"] += 1
            return calls["n"] == 1  # première vérification → collision, ensuite libre

        with patch("jobs.utils.sudo_exists", side_effect=exists):
            result = unique_archive_name("instance_app_20260511", "/backups")
        assert result == "instance_app_20260511_2"

    def test_trois_collisions(self):
        from jobs.utils import unique_archive_name
        calls = {"n": 0}

        def exists(path):
            calls["n"] += 1
            return calls["n"] <= 3  # base, _2, _3 occupés ; _4 libre

        with patch("jobs.utils.sudo_exists", side_effect=exists):
            result = unique_archive_name("instance_app_20260511", "/backups")
        assert result == "instance_app_20260511_4"

    def test_chemin_correct_transmis(self):
        from jobs.utils import unique_archive_name
        seen_paths = []

        def exists(path):
            seen_paths.append(path)
            return False

        with patch("jobs.utils.sudo_exists", side_effect=exists):
            unique_archive_name("myarchive", "/var/backups")

        assert seen_paths == ["/var/backups/myarchive.tar"]
