import json
import sqlite3
from decimal import ROUND_HALF_UP, Decimal

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 (
    DynamoDBPersistenceLayer,
    KeyPair,
)
from sqlite_utils import Database

from boto3clients import dynamodb_client
from config import ORDER_TABLE, SQLITE_DATABASE, SQLITE_TABLE

sqlite3.register_converter('json', json.loads)

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:
    new_image = event.detail['new_image']
    now_ = now()
    items = new_image['items']
    new_items: list[dict] = []

    for item in items:
        course = _get_course(item['id'])
        unit_price = Decimal(item['unit_price'])

        new_items.append(
            item
            | {
                'unit_price': unit_price.quantize(
                    Decimal('0.01'), rounding=ROUND_HALF_UP
                )
            }
            | (
                {
                    'id': course.get('metadata__betaeducacao_id'),
                }
                if course
                else {}
            )
        )

    order_layer.update_item(
        key=KeyPair(new_image['id'], 'items'),
        update_expr='SET #items = :items, updated_at = :updated_at',
        expr_attr_names={'#items': 'items'},
        expr_attr_values={':items': new_items, ':updated_at': now_},
    )

    return True


def _get_course(course_id: str) -> dict | None:
    with sqlite3.connect(
        database=SQLITE_DATABASE, detect_types=sqlite3.PARSE_DECLTYPES
    ) as conn:
        db = Database(conn)
        rows = db[SQLITE_TABLE].rows_where('id = ?', [course_id])

        for row in rows:
            return row['json']

    return None
