from io import StringIO

from django.core.cache import cache
from django.core.management import call_command
from django.test import TestCase, override_settings
from rest_framework.test import APIClient

from flower.app_version import APP_VERSION_CACHE_KEY


class AppVersionAPITest(TestCase):
    def setUp(self):
        cache.delete(APP_VERSION_CACHE_KEY)
        self.client = APIClient()

    def tearDown(self):
        cache.delete(APP_VERSION_CACHE_KEY)

    @override_settings(
        APP_LATEST_VERSION_MAJOR=1,
        APP_LATEST_VERSION_MINOR=2,
        APP_LATEST_VERSION_BUILD=345,
        APP_DOWNLOAD_URL="https://example.com/app.apk",
    )
    def test_app_version_api_returns_settings_payload_without_auth(self):
        response = self.client.get("/api/app-version/")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            response.data,
            {
                "latest_version": {
                    "major": 1,
                    "minor": 2,
                    "build": 345,
                },
                "download_url": "https://example.com/app.apk",
            },
        )

    def test_set_app_version_command_updates_cached_api_payload(self):
        output = StringIO()
        call_command(
            "set_app_version",
            "--major",
            "2",
            "--minor",
            "5",
            "--build",
            "1001",
            "--download-url",
            "https://example.com/latest.apk",
            stdout=output,
        )

        response = self.client.get("/api/app-version/")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data["latest_version"], {"major": 2, "minor": 5, "build": 1001})
        self.assertEqual(response.data["download_url"], "https://example.com/latest.apk")
        self.assertIn("'build': 1001", output.getvalue())
