from unittest import TestCase
import os
from pygeai.auth.clients import AuthClient
from pygeai.core.common.exceptions import APIResponseError 


class TestAuthGetProjectApiTokenIntegration(TestCase):
    __token_attrs = [
        'description', 'id', 'name', 'scope', 'status', 'timestamp'
    ]    

    def setUp(self):
        """
        Set up the test environment.
        """
        self.auth_client = AuthClient(alias="org")
        
        # Load API token ID from system environment variable
        self.api_token_id = os.getenv("TEST_API_TOKEN_ID")
        if not self.api_token_id:
            raise ValueError("TEST_API_TOKEN_ID environment variable must be set for integration tests")


    def __get_project_api_token(self, api_token_id=None):
        """
        Helper method to call get_project_api_token with default or custom parameters.
        """
        return self.auth_client.get_project_api_token(
            api_token_id=api_token_id if api_token_id is not None else self.api_token_id
        )


    def test_get_project_api_token_valid_id(self):
        """Test successful retrieval of project API token with valid token ID."""
        response = self.__get_project_api_token()

        # Validate response structure
        for token_attr in self.__token_attrs:
            self.assertIn(token_attr, response, f"Response should have a '{token_attr}' key")

        # Validate specific attributes
        self.assertEqual(response["id"], self.api_token_id, "Token ID should match requested ID")
        self.assertIsInstance(response["name"], str, "Token name should be a string")
        self.assertEqual(response["status"], "Active", "Status should be valid")


    def test_get_project_api_token_invalid_id_format(self):
        """Test error when using invalid token ID format."""
        invalid_ids = [
            "invalid-token-id",
            "12345",
            "not-a-uuid"
        ]
        
        for invalid_id in invalid_ids:
            with self.subTest(invalid_id=invalid_id):
                with self.assertRaises(APIResponseError) as exception:
                    self.__get_project_api_token(api_token_id=invalid_id)

                self.assertIn(
                    "not found",
                    str(exception.exception).lower(),
                    f"Expected error about invalid token ID format for {invalid_id}"
                )


    def test_get_project_api_token_empty_id(self):
        """Test error when token ID is empty."""
        with self.assertRaises(APIResponseError) as exception:
            self.__get_project_api_token(api_token_id="")

        self.assertIn(
            "Method Not Allowed",
            str(exception.exception),
            "Expected error about empty token ID"
        )    


    def test_get_project_api_token_unauthorized_access(self):
        """Test error when user doesn't have access to the token."""
        # Create a client with invalid credentials
        unauthorized_client = AuthClient(api_key="invalid", base_url="https://api.beta.saia.ai")
        
        with self.assertRaises(APIResponseError) as exception:
            unauthorized_client.get_project_api_token(api_token_id=self.api_token_id)

        self.assertIn(
            "Unauthorized",
            str(exception.exception),
            "Expected authorization-related error message"
        )