from __future__ import annotations

import sqlalchemy as sa
from sqlalchemy.orm import Session

from backend.app.db.models import User
from backend.app.models import UserCreate
from backend.app.repositories.base import BaseRepository


class UserRepository(BaseRepository[User]):
    """Data access helpers for user accounts."""

    model = User

    def __init__(self, session: Session) -> None:
        super().__init__(session)

    def get_by_username(self, username: str) -> User | None:
        statement = sa.select(self.model).where(
            sa.func.lower(self.model.username) == username.lower()
        )
        return self.session.scalar(statement)

    def list_recent(self, limit: int = 50) -> list[User]:
        statement = (
            sa.select(self.model).order_by(self.model.created_at.desc()).limit(limit)
        )
        return list(self.session.scalars(statement))

    def create(self, data: UserCreate) -> User:
        user = User(
            username=data.username,
            email=data.email,
            full_name=data.full_name,
            password_hash=data.password_hash,
            role=data.role,
            preferences=data.preferences,
        )
        self.session.add(user)
        return user
