from unittest.mock import MagicMock, patch

import pytest

from .package_description import KnownPackages, PackageDescription
from .uploader import BadCodebergCredentialsException, CodebergUploader


def test_from_env(monkeypatch):
    monkeypatch.setenv("CODEBERG_USER", "user")
    monkeypatch.setenv("CODEBERG_TOKEN", "token")

    uploader = CodebergUploader.from_env()

    assert uploader.user == "user"
    assert uploader.token == "token"


def test_from_env_bad_credentials(monkeypatch):
    monkeypatch.setenv("CODEBERG_USER", "")
    monkeypatch.setenv("CODEBERG_TOKEN", "")

    with pytest.raises(BadCodebergCredentialsException):
        CodebergUploader.from_env()


@patch("requests.put")
def test_upload_file(requests_mock, tmp_path):
    uploader = CodebergUploader("user", "token")
    package = PackageDescription(KnownPackages.connect, "1.2.3")
    file = tmp_path / "file.txt"

    with open(file, "w") as f:
        f.write("test")

    uploader.upload_file(package, "file.txt", file)

    requests_mock.assert_called_once()


@patch("requests.delete")
def test_delete_file(requests_mock):
    requests_mock.return_value = MagicMock(status_code=204)
    uploader = CodebergUploader("user", "token")
    package = PackageDescription(KnownPackages.connect, "1.2.3")

    uploader.delete_file(package, "file.txt")

    requests_mock.assert_called_once()
