from uuid import UUID

from src.infrastructure.clients.cognito_idp_client import CognitoIdpClientProtocol


class CredentialManager:
    def __init__(self, client: CognitoIdpClientProtocol) -> None:
        self.client = client

    def issue_m2m(self, tenant_id: UUID) -> str:
        """M2M認証用の資格情報を発行します。"""
        return self.client.create_user_pool_client(
            client_name=str(tenant_id),
            params={
                "GenerateSecret": True,
                "AccessTokenValidity": 24,
                "TokenValidityUnits": {
                    "AccessToken": "hours",
                },
                "EnableTokenRevocation": True,
                "AllowedOAuthFlowsUserPoolClient": True,
                "AllowedOAuthFlows": [
                    "client_credentials",
                ],
                "AllowedOAuthScopes": [
                    "m2m/management",
                ],
                "ExplicitAuthFlows": [
                    "CUSTOM_AUTH_FLOW_ONLY",
                ],
            },
        )

    def issue_user_login(self, tenant_id: UUID) -> str:
        """ユーザー認証用の資格情報を発行します。"""
        return self.client.create_user_pool_client(
            client_name=str(tenant_id),
            params={
                "GenerateSecret": False,
                "RefreshTokenValidity": 30,
                "AccessTokenValidity": 60,
                "IdTokenValidity": 60,
                "TokenValidityUnits": {
                    "RefreshToken": "days",
                    "AccessToken": "minutes",
                    "IdToken": "minutes",
                },
                "EnableTokenRevocation": True,
                "ExplicitAuthFlows": [
                    "ALLOW_USER_SRP_AUTH",
                    "ALLOW_REFRESH_TOKEN_AUTH",
                ],
                "ReadAttributes": [
                    "custom:tenant_id",
                    "custom:user_id",
                ],
                "WriteAttributes": [
                    "email",
                    "preferred_username",
                ],
                "SupportedIdentityProviders": [
                    "COGNITO",
                ],
                "PreventUserExistenceErrors": "ENABLED",
            },
        )

    def delete(self, credential_id: str) -> None:
        """資格情報を削除します。"""
        self.client.delete_user_pool_client(
            credential_id,
        )
