import psycopg
from aws_lambda_powertools.utilities.typing import LambdaContext
from src.infrastructure.repositories.contract_provider_repository import ContractProviderRepository
from src.settings import Settings

settings = Settings()


def handler(event: dict, _: LambdaContext) -> dict:
    with psycopg.connect(settings.postgres_url) as connection:
        contract_provider_repository = ContractProviderRepository(
            connection=connection,
        )
        application_client_id = event.get("callerContext", {}).get("clientId")
        if not application_client_id:
            raise KeyError("application_client_id is required in the event request.")

        contract_provider = contract_provider_repository.get_by_application_client_id(application_client_id)

        # アクセス トークンの生成時にContract Provider IDをクレームとして追加
        event["response"] = {
            "claimsAndScopeOverrideDetails": {
                "accessTokenGeneration": {
                    "claimsToAddOrOverride": {
                        "contract_provider_id": str(contract_provider.id),
                    },
                },
            },
        }
    return event
