# (c) cavaliba.com - tests / api


from django.test import TestCase
from django.urls import reverse

import app_home.cache as cache
from app_data.data import Instance
from tests import helper


class APIKeyTest(TestCase):
    def setUp(self):
        cache.clear()

    # API HOME

    def test_api_root(self):
        # helper.add_apikey_admin()
        response = self.client.get(reverse("api:api"))
        self.assertEqual(response.status_code, 401)

    def test_api_ping(self):
        # helper.add_apikey_admin()
        response = self.client.get(reverse("api:api_ping"))
        self.assertEqual(response.status_code, 200)

    def test_api_version(self):
        header = helper.add_apikey_admin()
        response = self.client.get(
            reverse("api:api_version"),
            headers=header,
        )
        self.assertEqual(response.status_code, 200)

    def test_api_version_output_formats(self):
        header = helper.add_apikey_admin()

        # Test JSON format (default)
        response = self.client.get(
            reverse("api:api_version"),
            headers=header,
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response["Content-Type"], "application/json; charset=utf-8")

        # Test JSON format (explicit)
        response = self.client.get(
            reverse("api:api_version") + "?o=json",
            headers=header,
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response["Content-Type"], "application/json; charset=utf-8")

        # Test YAML format
        response = self.client.get(
            reverse("api:api_version") + "?o=yaml",
            headers=header,
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response["Content-Type"], "application/x-yaml; charset=utf-8")

        # Test TXT format
        response = self.client.get(
            reverse("api:api_version") + "?o=txt",
            headers=header,
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response["Content-Type"], "text/plain; charset=utf-8")

    def test_api_key_disabled(self):
        instance = Instance(classname="_apikey", keyname="test")
        data = {
            "secret": "mysecret",
            "ip_filter": "*",
            "is_readonly": False,
            "is_enabled": False,
            "acl": "role:role_admin",
        }
        instance.merge_import(data)
        instance.create()

        response = self.client.get(
            reverse("api:api_version"),
            headers={"X-Cavaliba-Key": "test mysecret"},
        )
        self.assertEqual(response.status_code, 401)

    def test_api_badsecret(self):
        header = helper.add_apikey_admin()
        response = self.client.get(
            reverse("api:api_version"),
            headers={"X-Cavaliba-Key": "test badsecret"},
        )
        self.assertEqual(response.status_code, 401)
