from aws_lambda_powertools.utilities.typing import LambdaContext
from layercake.dateutils import now
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair

import events.billing.cancel_enrollment as app
from utils import get_billing_period

enrollment_id = '77055ad7-03e1-4b07-98dc-a2f1a90913ba'
event = {
    'detail': {
        'new_image': {
            'id': enrollment_id,
            'sk': '0',
            'user': {
                'id': '5OxmMjL-ujoR5IMGegQz',
                'name': 'Sérgio R Siqueira',
            },
            'course': {
                'id': '123',
                'name': 'pytest',
            },
        }
    }
}


def test_cancel_enrollment(
    dynamodb_seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    lambda_context: LambdaContext,
):
    now_ = now()
    start_period, end_period = get_billing_period(
        billing_day=6,
        date_=now_,
    )
    pk = 'BILLING#ORG#cJtK9SsnJhKPyxESe7g3DG'
    sk = 'START#{start}#END#{end}#ENROLLMENT#{enrollment_id}'.format(
        start=start_period.isoformat(),
        end=end_period.isoformat(),
        enrollment_id=enrollment_id,
    )
    # Add up-to-date enrollment item to billing
    dynamodb_persistence_layer.put_item(
        item={
            'id': pk,
            'sk': sk,
            'unit_price': 100,
            'course': {'id': '123', 'name': 'pytest'},
            'user': {'id': '5OxmMjL-ujoR5IMGegQz', 'name': 'Sérgio R Siqueira'},
            'enrolled_at': now_,
        }
    )

    event['detail']['new_image']['created_at'] = now_.isoformat()
    assert app.lambda_handler(event, lambda_context)  # type: ignore

    r = dynamodb_persistence_layer.collection.query(KeyPair(pk, sk))
    assert len(r['items']) == 2
    assert sum(x['unit_price'] for x in r['items']) == 0


def test_cancel_old_enrollment(
    dynamodb_seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    lambda_context: LambdaContext,
):
    event['detail']['new_image']['created_at'] = '2025-06-05T12:13:54.371416+00:00'
    assert not app.lambda_handler(event, lambda_context)  # type: ignore
