import datetime
from typing import Annotated

from fastapi import Cookie, Depends, Header
from sqlmodel import select
from rvpc.auth.admin import MatchingLocLogin
from rvpc.db import SessionDep
from rvpc.models.models import TrustedDevice


async def check_device(
    session: SessionDep,
    user_agent: Annotated[str, Header()],
    location: Annotated[str | None, Cookie()] = None,
    device: Annotated[str | None, Cookie()] = None,
):
    return session.exec(
        select(TrustedDevice).where(
            TrustedDevice.location_name == location,
            TrustedDevice.user_agent == user_agent,
            TrustedDevice.id == device,
        )
    ).one_or_none()


MatchingDevice = Annotated[TrustedDevice | None, Depends(check_device)]


async def create_or_update_device(
    session: SessionDep,
    matching_device: MatchingDevice,
    matching_loc: MatchingLocLogin,
    user_agent: Annotated[str, Header()],
):
    if matching_device is None:
        stmt = select(TrustedDevice).where(
            TrustedDevice.location_name == matching_loc.name
        )
        existing_device = session.exec(stmt).one_or_none()

        if existing_device is not None:
            session.delete(existing_device)
            session.commit()

        trusted_device = TrustedDevice(
            location_name=matching_loc.name,
            user_agent=user_agent,
            last_used=datetime.datetime.now(),
        )
        session.add(trusted_device)
        session.commit()
        session.refresh(trusted_device)

        return trusted_device

    matching_device.last_used = datetime.datetime.now()

    session.add(matching_device)
    session.commit()
    session.refresh(matching_device)

    return matching_device


NewOrExistingDevice = Annotated[
    TrustedDevice, Depends(create_or_update_device)
]
