from typing import Optional, Dict, Any, List
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, desc
from sqlalchemy.orm import selectinload
from datetime import datetime

from app.models.activity_log import ActivityLog
from app.models.staff.staff_model import Staff


class ActivityLogService:
    """Service for logging and retrieving user activities"""
    
    def __init__(self, db: AsyncSession):
        self.db = db
    
    async def log_activity(
        self,
        chain_id: int,
        staff_id: int,
        action_type: str,
        entity_type: str,
        description: str,
        entity_id: Optional[int] = None,
        metadata: Optional[Dict[str, Any]] = None
    ) -> ActivityLog:
        """
        Log an activity
        
        Args:
            chain_id: Chain ID of the user
            staff_id: Staff ID who performed the action
            action_type: Type of action (e.g., "CREATE_LISTING", "UPDATE_LISTING", "DELETE_LISTING", "APPROVE_LISTING")
            entity_type: Type of entity (e.g., "LISTING", "PRODUCT", "CATEGORY")
            description: Human-readable description
            entity_id: Optional ID of the affected entity
            metadata: Optional additional data
        
        Returns:
            Created ActivityLog
        """
        activity_log = ActivityLog(
            chain_id=chain_id,
            staff_id=staff_id,
            action_type=action_type,
            entity_type=entity_type,
            entity_id=entity_id,
            description=description,
            action_metadata=metadata
        )
        
        self.db.add(activity_log)
        await self.db.commit()
        await self.db.refresh(activity_log)
        
        return activity_log
    
    async def get_activity_logs(
        self,
        chain_id: int,
        skip: int = 0,
        limit: int = 100,
        staff_id: Optional[int] = None,
        action_type: Optional[str] = None,
        entity_type: Optional[str] = None,
        start_date: Optional[datetime] = None,
        end_date: Optional[datetime] = None
    ) -> List[ActivityLog]:
        """
        Get activity logs for a chain (admin only)
        
        Args:
            chain_id: Chain ID to filter logs
            skip: Number of records to skip
            limit: Maximum number of records to return
            staff_id: Optional filter by staff ID
            action_type: Optional filter by action type
            entity_type: Optional filter by entity type
            start_date: Optional filter by start date
            end_date: Optional filter by end date
        
        Returns:
            List of ActivityLog records
        """
        stmt = select(ActivityLog).options(
            selectinload(ActivityLog.staff)
        ).where(ActivityLog.chain_id == chain_id)
        
        # Apply filters
        if staff_id:
            stmt = stmt.where(ActivityLog.staff_id == staff_id)
        if action_type:
            stmt = stmt.where(ActivityLog.action_type == action_type)
        if entity_type:
            stmt = stmt.where(ActivityLog.entity_type == entity_type)
        if start_date:
            stmt = stmt.where(ActivityLog.created_at >= start_date)
        if end_date:
            stmt = stmt.where(ActivityLog.created_at <= end_date)
        
        # Order by most recent first
        stmt = stmt.order_by(desc(ActivityLog.created_at)).offset(skip).limit(limit)
        
        result = await self.db.execute(stmt)
        return result.scalars().all()

