import contextlib
from collections.abc import Sequence

from sqlalchemy import insert, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession

from template_project.adapters.data_gateways.tables import key_skills_table


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

    async def query(self, query: str) -> Sequence[str]:
        statement = (
            select(key_skills_table.c.name)
            .where(key_skills_table.c.name.ilike(f"%{query}%"))
            .order_by(key_skills_table.c.name)
            .limit(30)
        )
        result = await self._session.execute(statement)
        return result.scalars().all()

    async def add_skills(self, name: list[str]) -> None:
        insert_statement = insert(key_skills_table).values([{"name": _} for _ in name])
        with contextlib.suppress(IntegrityError):
            await self._session.execute(insert_statement)
