"""
Admin Service - Users Module

包含用户管理相关功能。
"""

import logging
from typing import Optional, Dict, Any, Tuple, List

from sqlmodel import Session, select, func
from datetime import datetime

from src.config.database import engine
from src.models.entities import UserDB
from src.models.admin_schemas import AdminUserListItem

logger = logging.getLogger(__name__)


def _timestamp_to_iso(ts: Optional[float]) -> str:
    """Convert timestamp to ISO format string"""
    if not ts:
        return ""
    return datetime.fromtimestamp(ts).isoformat()


class UserManagementService:
    """User management service for admin operations"""

    async def list_users(
        self,
        page: int = 1,
        page_size: int = 20,
        filters: Optional[Dict[str, Any]] = None,
        sort_by: str = "created_at",
        sort_order: str = "desc",
    ) -> Tuple[List[AdminUserListItem], int]:
        """List users with pagination and filtering"""
        with Session(engine) as session:
            query = select(UserDB)

            # Apply filters
            if filters:
                if filters.get("is_active") is not None:
                    query = query.where(UserDB.is_active == filters["is_active"])
                if filters.get("is_superuser") is not None:
                    query = query.where(UserDB.is_superuser == filters["is_superuser"])
                if filters.get("search"):
                    search = f"%{filters['search']}%"
                    query = query.where(
                        (UserDB.username.ilike(search)) | (UserDB.email.ilike(search))
                    )

            # Get total count
            total = session.exec(
                select(func.count()).select_from(query.subquery())
            ).one()

            # Apply sorting
            if sort_by == "created_at":
                sort_column = UserDB.created_at
            elif sort_by == "username":
                sort_column = UserDB.username
            elif sort_by == "last_login":
                sort_column = UserDB.last_login
            else:
                sort_column = UserDB.created_at

            if sort_order.lower() == "desc":
                query = query.order_by(sort_column.desc())
            else:
                query = query.order_by(sort_column.asc())

            # Apply pagination
            offset = (page - 1) * page_size
            query = query.offset(offset).limit(page_size)

            users = session.exec(query).all()

            items = [
                AdminUserListItem(
                    id=user.id,
                    username=user.username,
                    email=user.email,
                    is_active=user.is_active,
                    is_superuser=user.is_superuser,
                    permissions=user.permissions or [],
                    roles=user.roles or [],
                    avatar_url=user.avatar_url,
                    created_at=_timestamp_to_iso(user.created_at),
                    last_login=_timestamp_to_iso(user.last_login),
                )
                for user in users
            ]

            return items, total

    async def get_user(self, user_id: str) -> Optional[AdminUserListItem]:
        """Get user by ID"""
        with Session(engine) as session:
            user = session.exec(select(UserDB).where(UserDB.id == user_id)).first()

            if not user:
                return None

            return AdminUserListItem(
                id=user.id,
                username=user.username,
                email=user.email,
                is_active=user.is_active,
                is_superuser=user.is_superuser,
                permissions=user.permissions or [],
                roles=user.roles or [],
                avatar_url=user.avatar_url,
                created_at=user.created_at,
                last_login=user.last_login,
            )

    async def update_user(
        self, user_id: str, update_data: Dict[str, Any]
    ) -> Optional[AdminUserListItem]:
        """Update user information"""
        with Session(engine) as session:
            user = session.exec(select(UserDB).where(UserDB.id == user_id)).first()

            if not user:
                return None

            # Update allowed fields
            allowed_fields = ["email", "is_active", "is_superuser", "permissions", "roles"]
            for field in allowed_fields:
                if field in update_data:
                    setattr(user, field, update_data[field])

            user.updated_at = datetime.now().timestamp()
            session.add(user)
            session.commit()
            session.refresh(user)

            return AdminUserListItem(
                id=user.id,
                username=user.username,
                email=user.email,
                is_active=user.is_active,
                is_superuser=user.is_superuser,
                permissions=user.permissions or [],
                roles=user.roles or [],
                avatar_url=user.avatar_url,
                created_at=user.created_at,
                last_login=user.last_login,
            )

    async def toggle_user_active(self, user_id: str, is_active: bool) -> Optional[AdminUserListItem]:
        """Toggle user active status"""
        return await self.update_user(user_id, {"is_active": is_active})

    async def delete_user(self, user_id: str) -> bool:
        """Delete a user"""
        with Session(engine) as session:
            user = session.exec(select(UserDB).where(UserDB.id == user_id)).first()

            if not user:
                return False

            session.delete(user)
            session.commit()
            return True
