from typing import override

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from template_project.adapters.data_gateways.tables import auth_identity_table
from template_project.application.auth_identity.data_gateway import AuthIdentityDataGateway
from template_project.application.auth_identity.entity import AuthIdentity, AuthMethod
from template_project.application.user.entity import UserId


class DefaultAuthIdentityDataGateway(AuthIdentityDataGateway):
    def __init__(self, session: AsyncSession) -> None:
        self._session = session

    @override
    async def load_by_method_and_identifier(self, method: AuthMethod, identifier: str) -> AuthIdentity | None:
        statement = select(AuthIdentity).where(
            auth_identity_table.c.method == method, auth_identity_table.c.identifier == identifier
        )
        result = await self._session.execute(statement)
        return result.scalar_one_or_none()

    @override
    async def load_all_for_user(self, user_id: UserId) -> list[AuthIdentity]:
        statement = select(AuthIdentity).where(auth_identity_table.c.user_id == user_id)
        result = await self._session.execute(statement)
        return list(result.scalars().all())
