from aws_lambda_powertools import Logger
from aws_lambda_powertools.utilities.data_classes import (
    EventBridgeEvent,
    event_source,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
from layercake.dateutils import now
from layercake.dynamodb import (
    ComposeKey,
    DynamoDBPersistenceLayer,
    KeyPair,
)

from boto3clients import dynamodb_client
from config import ORDER_TABLE

logger = Logger(__name__)
order_layer = DynamoDBPersistenceLayer(ORDER_TABLE, dynamodb_client)


@event_source(data_class=EventBridgeEvent)
@logger.inject_lambda_context
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
    """Set the order status to `EXPIRED` 24 hours after it becomes overdue."""
    new_image = event.detail['new_image']
    now_ = now()

    try:
        order_layer.update_item(
            key=KeyPair(new_image['id'], '0'),
            update_expr='SET #status = :expired, updated_at = :updated_at',
            cond_expr='#status IN (:pending) and payment_method = :payment_method',
            expr_attr_names={
                '#status': 'status',
            },
            expr_attr_values={
                ':expired': 'EXPIRED',
                ':pending': 'PENDING',
                ':payment_method': 'MANUAL',
                ':updated_at': now_,
            },
        )
    except Exception:
        logger.info('Failed to update status to EXPIRED', order_id=new_image['id'])
        order_layer.put_item(
            item={
                'id': new_image['id'],
                'sk': ComposeKey('failed', prefix=new_image['sk']),
                'created_at': now_,
            }
        )

        return False
    else:
        logger.info('Status set to EXPIRED', order_id=new_image['id'])
        order_layer.put_item(
            item={
                'id': new_image['id'],
                'sk': ComposeKey('completed', prefix=new_image['sk']),
                'created_at': now_,
            }
        )

        return True
