"""Tests for authentication resource."""

import pytest
from pytest_httpx import HTTPXMock

from contiss import Contiss
from contiss.exceptions import AuthenticationError, ConflictError, NotFoundError


def test_create_api_key(mock_jwt_token, httpx_mock: HTTPXMock):
    """Test creating an API key."""
    response = {
        "key": "sk_live_newkey12345678901234567890123456789012",
        "id": "key_abc123",
        "name": "Test Key",
        "key_prefix": "sk_live_newkey12",
        "created_at": "2026-01-02T10:00:00Z",
        "expires_at": None,
    }

    httpx_mock.add_response(
        url="https://api.contiss.ai/auth/api-keys", json=response, method="POST"
    )

    client = Contiss(token=mock_jwt_token)
    api_key = client.auth.create_api_key(name="Test Key")

    assert api_key.key.startswith("sk_live_")
    assert api_key.name == "Test Key"
    assert api_key.id == "key_abc123"
    client.close()


def test_create_api_key_with_expiration(mock_jwt_token, httpx_mock: HTTPXMock):
    """Test creating an API key with expiration."""
    response = {
        "key": "sk_live_newkey12345678901234567890123456789012",
        "id": "key_abc123",
        "name": "Expiring Key",
        "key_prefix": "sk_live_newkey12",
        "created_at": "2026-01-02T10:00:00Z",
        "expires_at": "2026-04-02T10:00:00Z",
    }

    httpx_mock.add_response(
        url="https://api.contiss.ai/auth/api-keys", json=response, method="POST"
    )

    client = Contiss(token=mock_jwt_token)
    api_key = client.auth.create_api_key(name="Expiring Key", expires_in_days=90)

    assert api_key.expires_at is not None
    client.close()


def test_list_api_keys(mock_jwt_token, httpx_mock: HTTPXMock):
    """Test listing API keys."""
    response = {
        "keys": [
            {
                "id": "key_abc123",
                "name": "Production Key",
                "key_prefix": "sk_live_abc12345",
                "last_used_at": "2026-01-02T09:00:00Z",
                "expires_at": None,
                "created_at": "2026-01-01T10:00:00Z",
            },
            {
                "id": "key_def456",
                "name": "Development Key",
                "key_prefix": "sk_test_def67890",
                "last_used_at": None,
                "expires_at": "2026-04-01T10:00:00Z",
                "created_at": "2026-01-01T11:00:00Z",
            },
        ]
    }

    httpx_mock.add_response(
        url="https://api.contiss.ai/auth/api-keys", json=response, method="GET"
    )

    client = Contiss(token=mock_jwt_token)
    api_keys = client.auth.list_api_keys()

    assert len(api_keys.keys) == 2
    assert api_keys.keys[0].name == "Production Key"
    assert api_keys.keys[1].name == "Development Key"
    client.close()


def test_delete_api_key(mock_jwt_token, httpx_mock: HTTPXMock):
    """Test deleting an API key."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/auth/api-keys/key_abc123",
        json={"success": True},
        method="DELETE",
    )

    client = Contiss(token=mock_jwt_token)
    success = client.auth.delete_api_key(key_id="key_abc123")

    assert success is True
    client.close()


def test_delete_api_key_not_found(mock_jwt_token, httpx_mock: HTTPXMock):
    """Test deleting a non-existent API key."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/auth/api-keys/invalid_key",
        status_code=404,
        json={"error": "not_found", "message": "API key not found"},
        method="DELETE",
    )

    client = Contiss(token=mock_jwt_token)
    with pytest.raises(NotFoundError):
        client.auth.delete_api_key(key_id="invalid_key")
    client.close()


def test_create_api_key_requires_jwt(mock_api_key, httpx_mock: HTTPXMock):
    """Test that creating API key requires JWT (not API key)."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/auth/api-keys",
        status_code=401,
        json={"error": "unauthorized", "message": "JWT token required"},
        method="POST",
    )

    client = Contiss(api_key=mock_api_key)  # Using API key, not JWT
    with pytest.raises(AuthenticationError):
        client.auth.create_api_key(name="Test")
    client.close()
