"""Minimal integration tests for DynamoDB adapter."""

import uuid
from datetime import UTC, datetime

import pytest

from augint_billing_lib.models import Link


@pytest.mark.integration
class TestDdbIntegration:
    """Test DynamoDB adapter with real AWS resources."""

    # Note: dynamodb_table, repo, and test_link fixtures are now provided by conftest.py
    # They include automatic cleanup after each test

    def test_save_and_get_by_api_key(self, repo, test_link):
        """Test saving and retrieving link by API key."""
        # Save link
        repo.save(test_link)

        # Retrieve by API key
        retrieved = repo.get_by_api_key(test_link.api_key_id)

        assert retrieved is not None
        assert retrieved.api_key_id == test_link.api_key_id
        assert retrieved.stripe_customer_id == test_link.stripe_customer_id
        assert retrieved.plan == test_link.plan
        assert retrieved.usage_plan_id == test_link.usage_plan_id

    def test_get_by_customer(self, repo, test_link):
        """Test retrieving link by Stripe customer ID."""
        import time

        # Save link
        repo.save(test_link)

        # Wait for GSI consistency (GSIs are eventually consistent)
        time.sleep(1)

        # Retrieve by customer ID - returns a list
        retrieved_list = repo.get_by_customer(test_link.stripe_customer_id)

        assert len(retrieved_list) >= 1
        retrieved = retrieved_list[0]
        assert retrieved.api_key_id == test_link.api_key_id
        assert retrieved.stripe_customer_id == test_link.stripe_customer_id

    def test_scan_metered(self, repo):
        """Test scanning for metered customers."""
        # Create and save metered customers - note: lowercase 'metered' in the plan field
        metered_links = []
        for _i in range(3):
            link = Link(
                api_key_id=f"metered-key-{uuid.uuid4()}",
                stripe_customer_id=f"cus_metered_{uuid.uuid4().hex[:8]}",
                plan="metered",  # lowercase to match scan filter
                usage_plan_id="METERED",
                metered_subscription_item_id=f"si_test_{uuid.uuid4().hex[:8]}",
            )
            repo.save(link)
            metered_links.append(link)

        # Scan for metered customers
        result = repo.scan_metered()

        # Check that our metered customers are in the results
        result_api_keys = {link.api_key_id for link in result}
        for link in metered_links:
            assert link.api_key_id in result_api_keys

    def test_update_existing_link(self, repo, test_link):
        """Test updating an existing link."""
        # Save initial link
        repo.save(test_link)

        # Update link (use lowercase 'metered' to match Literal type)
        test_link.plan = "metered"
        test_link.metered_subscription_item_id = "si_test_123"
        test_link.last_reported_usage_ts = datetime.now(UTC)
        repo.save(test_link)

        # Retrieve and verify update
        retrieved = repo.get_by_api_key(test_link.api_key_id)
        assert retrieved.plan == "metered"  # lowercase to match Literal type
        assert retrieved.metered_subscription_item_id == "si_test_123"
        assert retrieved.last_reported_usage_ts is not None

    def test_get_nonexistent_by_api_key(self, repo):
        """Test retrieving non-existent link by API key."""
        with pytest.raises(KeyError):
            repo.get_by_api_key("nonexistent-key")

    def test_get_nonexistent_by_customer(self, repo):
        """Test retrieving non-existent link by customer ID."""
        result = repo.get_by_customer("cus_nonexistent")
        assert result == []  # Returns empty list, not None
