from datetime import timedelta

from aws_lambda_powertools.utilities.typing import LambdaContext
from layercake.dateutils import now
from layercake.dynamodb import (
    DynamoDBPersistenceLayer,
    SortKey,
    TransactKey,
)

import events.reporting.append_cert as app


def test_append_cert(
    seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    lambda_context: LambdaContext,
):
    cert_expires_at = now() + timedelta(days=360)
    event = {
        'detail': {
            'new_image': {
                'id': 'e45019d8-be7a-4a82-9b37-12a01f0127bb',
                'sk': '0',
                'course': {
                    'id': '431',
                    'name': 'How to Sing Better',
                },
                'cert_expires_at': cert_expires_at.isoformat(),
                'user': {
                    'id': '1234',
                    'name': 'Tobias Summit',
                },
                'org_id': '1e2eaf0e-e319-49eb-ab33-1ddec156dc94',
                'created_at': '2025-01-01T00:00:00-03:06',
                'completed_at': '2025-01-10T00:00:00-03:06',
            }
        }
    }
    assert app.lambda_handler(event, lambda_context)  # type: ignore

    # The reporting month is the month before the certificate expires
    report_month = (cert_expires_at.replace(day=1) - timedelta(days=1)).replace(day=1)
    report_sk = 'MONTH#{}#SCHEDULE#SEND_REPORT_EMAIL'.format(
        report_month.strftime('%Y-%m')
    )

    r = dynamodb_persistence_layer.collection.get_items(
        TransactKey('CERT_REPORTING#ORG#1e2eaf0e-e319-49eb-ab33-1ddec156dc94')
        + SortKey(
            sk=report_sk,
            rename_key='report_email',
        )
        + SortKey(
            sk='MONTH#{}#ENROLLMENT#e45019d8-be7a-4a82-9b37-12a01f0127bb'.format(
                cert_expires_at.strftime('%Y-%m')
            ),
            rename_key='enrollment',
        ),
        flatten_top=False,
    )

    assert 'course' in r['enrollment']
    assert 'ttl' in r['report_email']


def test_report_exists(
    seeds,
    dynamodb_persistence_layer: DynamoDBPersistenceLayer,
    lambda_context: LambdaContext,
):
    event = {
        'detail': {
            'new_image': {
                'id': 'e45019d8-be7a-4a82-9b37-12a01f0127bb',
                'sk': '0',
                'course': {
                    'id': '431',
                    'name': 'How to Sing Better',
                },
                'cert_expires_at': '2025-07-02T00:00:00-03:06',
                'user': {
                    'id': '1234',
                    'name': 'Tobias Summit',
                },
                'org_id': '00237409-9384-4692-9be5-b4443a41e1c4',
                'created_at': '2025-01-01T00:00:00-03:06',
                'completed_at': '2025-01-10T00:00:00-03:06',
            }
        }
    }
    assert app.lambda_handler(event, lambda_context)  # type: ignore
