import json
import os
from datetime import date
from functools import partial
from typing import Any

from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler.api_gateway import (
    APIGatewayHttpResolver,
    CORSConfig,
)
from aws_lambda_powertools.event_handler.exceptions import ServiceError
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.shared.json_encoder import Encoder
from aws_lambda_powertools.utilities.typing import LambdaContext

from api_gateway import JSONResponse
from middlewares import AuthenticationMiddleware
from routes import (
    courses,
    enrollments,
    lookup,
    orders,
    orgs,
    settings,
    users,
    webhooks,
)


class JSONEncoder(Encoder):
    def default(self, obj):
        if isinstance(obj, date):
            return obj.isoformat()

        return super().default(obj)


tracer = Tracer()
logger = Logger(__name__)
cors = CORSConfig(
    allow_origin='*',
    allow_headers=['Content-Type', 'X-Requested-With', 'Authorization', 'X-Tenant'],
    max_age=600,
    allow_credentials=False,
)
app = APIGatewayHttpResolver(
    enable_validation=True,
    cors=cors,
    debug='AWS_SAM_LOCAL' in os.environ,
    serializer=partial(json.dumps, separators=(',', ':'), cls=JSONEncoder),
)
app.use(middlewares=[AuthenticationMiddleware()])
app.include_router(courses.router, prefix='/courses')
app.include_router(enrollments.router, prefix='/enrollments')
app.include_router(enrollments.slots, prefix='/enrollments')
app.include_router(enrollments.enroll, prefix='/enrollments')
app.include_router(enrollments.cancel, prefix='/enrollments')
app.include_router(enrollments.deduplication_window, prefix='/enrollments')
app.include_router(orders.router, prefix='/orders')
app.include_router(users.router, prefix='/users')
app.include_router(users.logs, prefix='/users')
app.include_router(users.emails, prefix='/users')
app.include_router(users.orgs, prefix='/users')
app.include_router(orgs.policies, prefix='/orgs')
app.include_router(webhooks.router, prefix='/webhooks')
app.include_router(settings.router, prefix='/settings')
app.include_router(lookup.router, prefix='/lookup')


@app.exception_handler(ServiceError)
def exc_error(exc: ServiceError):
    return JSONResponse(
        body={
            'type': type(exc).__name__,
            'message': str(exc),
        },
        status_code=exc.status_code,
    )


@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_HTTP)
@tracer.capture_lambda_handler
def lambda_handler(event: dict[str, Any], context: LambdaContext) -> dict[str, Any]:
    return app.resolve(event, context)
