from typing import List, Optional

from sqlalchemy import desc, func
from sqlalchemy.ext.asyncio.session import AsyncSession
from sqlalchemy.sql.expression import select

from app.database.dbo.mottak import Arkivuttrekk as Arkivuttrekk_DBO
from app.domain.models.Arkivuttrekk import Arkivuttrekk


async def create(db: AsyncSession, arkivuttrekk: Arkivuttrekk) -> Arkivuttrekk_DBO:
    dbo = Arkivuttrekk_DBO(**vars(arkivuttrekk))
    db.add(dbo)

    await db.flush()
    return dbo


async def update(db: AsyncSession, id_: int, updated_fields: dict) -> Optional[Arkivuttrekk_DBO]:
    arkivuttrekk = await db.get(Arkivuttrekk_DBO, id_)
    if not arkivuttrekk:
        return None

    for key, value in updated_fields.items():
        setattr(arkivuttrekk, key, value)

    await db.flush()
    return arkivuttrekk


async def get_all(db: AsyncSession, skip: int, limit: int) -> List[Arkivuttrekk_DBO]:
    query = await db.execute(
        select(Arkivuttrekk_DBO)
        .order_by(desc(Arkivuttrekk_DBO.id))
        # None is equivalent to no limit.
        .limit(None if limit == -1 else limit)
        .offset(skip)
    )
    return query.scalars().all()


async def get_count(db: AsyncSession) -> int:
    return await db.scalar(select(func.count(Arkivuttrekk_DBO.id)))


async def get_by_id(db: AsyncSession, id_: int) -> Optional[Arkivuttrekk_DBO]:
    return await db.get(Arkivuttrekk_DBO, id_)

from typing import List, Optional

from sqlalchemy import desc, func
from sqlalchemy.ext.asyncio.session import AsyncSession
from sqlalchemy.sql.expression import select

from app.database.dbo.mottak import Arkivuttrekk as Arkivuttrekk_DBO
from app.domain.models.Arkivuttrekk import Arkivuttrekk


async def create(db: AsyncSession, arkivuttrekk: Arkivuttrekk) -> Arkivuttrekk_DBO:
    dbo = Arkivuttrekk_DBO(**vars(arkivuttrekk))
    db.add(dbo)

    await db.flush()
    return dbo


async def update(db: AsyncSession, id_: int, updated_fields: dict) -> Optional[Arkivuttrekk_DBO]:
    arkivuttrekk = await db.get(Arkivuttrekk_DBO, id_)
    if not arkivuttrekk:
        return None

    for key, value in updated_fields.items():
        setattr(arkivuttrekk, key, value)

    await db.flush()
    return arkivuttrekk


async def get_all(db: AsyncSession, skip: int, limit: int) -> List[Arkivuttrekk_DBO]:
    query = await db.execute(
        select(Arkivuttrekk_DBO)
        .order_by(desc(Arkivuttrekk_DBO.id))
        # None is equivalent to no limit.
        .limit(None if limit == -1 else limit)
        .offset(skip)
    )
    return query.scalars().all()


async def get_count(db: AsyncSession) -> int:
    return await db.scalar(select(func.count(Arkivuttrekk_DBO.id)))


async def get_by_id(db: AsyncSession, id_: int) -> Optional[Arkivuttrekk_DBO]:
    return await db.get(Arkivuttrekk_DBO, id_)

# None is equivalent to no limit.