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


class TestAuthDeleteProjectApiTokenIntegration(TestCase):

    def setUp(self):
        """
        Set up the test environment.
        """
        self.auth_client = AuthClient(alias="org")
        self.project_id = "be4889df-cacc-4e6f-b3bb-153c4ac0d168"
        self.test_token_name = f"test_token_{uuid.uuid4().hex[:8]}"
        self.created_token = self.__load_api_token()

    def __load_api_token(self, project_id=None, name=None, description=None):
        """
        Helper method to call create_project_api_token with default or custom parameters.
        """
        return self.auth_client.create_project_api_token(
            project_id=project_id if project_id is not None else self.project_id,
            name=name if name is not None else self.test_token_name,
            description="Test token created during integration testing" if description is None else description
        )
    

    def __delete_project_api_token(self, api_token_id=None):
        """
        Helper method to call delete_project_api_token with default or custom parameters.
        """
        return self.auth_client.delete_project_api_token(
            api_token_id=api_token_id if api_token_id is not None else self.created_token["id"]
        )


    def test_delete_project_api_token_valid_id(self):
        """Test successful deletion of project API token with valid token ID."""
        response = self.__delete_project_api_token()

        # Validate response structure - should contain confirmation message
        self.assertIsInstance(response, dict, "Response should be a dictionary")


    def test_delete_project_api_token_invalid_token_id_format(self):
        """Test error when using invalid token ID format."""
        invalid_id = "invalid-token-id"
        
        with self.assertRaises(APIResponseError) as exception:
            self.__delete_project_api_token(api_token_id=invalid_id)

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


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

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


    def test_delete_project_api_token_unauthorized_access(self):
        """Test error when user doesn't have access to delete 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.delete_project_api_token(api_token_id=self.created_token["id"])

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


    def test_delete_project_api_token_whitespace_handling(self):
        """Test deletion with whitespace in token ID."""
        whitespace_ids = [
            f" {self.created_token}",      # Leading space
            f"{self.created_token} ",      # Trailing space
            f" {self.created_token} ",     # Both spaces
            f"\t{self.created_token}\n",   # Tab and newline
        ]
        
        for whitespace_id in whitespace_ids:
            with self.subTest(whitespace_id=repr(whitespace_id)):
                with self.assertRaises(APIResponseError) as exception:
                    self.__delete_project_api_token(api_token_id=whitespace_id)

            self.assertIn(
                "Not Found",
                str(exception.exception),
                f"Expected error for token ID with whitespace: {repr(whitespace_id)}"
            )

    
    def test_delete_project_api_token_idempotency(self):
        """Test that deleting the same token twice handles gracefully."""
        # First deletion
        self.__delete_project_api_token()
        
        # Second deletion - might succeed silently or return appropriate message
        with self.assertRaises(APIResponseError) as exception:
            self.__delete_project_api_token()

        self.assertIn(
            "Not Found",
            str(exception.exception),
            "Expected appropriate error for duplicate deletion"
        )