from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import desc

from app.database import get_db
from app.models.user import User, UserRole
from app.models.audit_log import AuditLog
from app.routers.auth import get_current_user
from pydantic import BaseModel
from datetime import datetime

router = APIRouter(
    prefix="/audit",
    tags=["audit"],
    responses={404: {"description": "Not found"}},
)

class AuditLogResponse(BaseModel):
    id: int
    user_id: Optional[int]
    username: Optional[str]
    event_type: str
    event_description: str
    ip_address: Optional[str]
    resource_type: Optional[str]
    resource_id: Optional[str]
    old_value: Optional[str] = None
    new_value: Optional[str] = None
    timestamp: datetime

    class Config:
        orm_mode = True

@router.get("/logs", response_model=List[AuditLogResponse])
async def get_audit_logs(
    skip: int = 0,
    limit: int = Query(100, le=1000, description="Max rows per page (cap 1000)"),
    user_id: Optional[int] = None,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Get audit logs.

    Admins see everything. Editors can scope the query to a single
    resource (e.g. resource_type='vulnerability', resource_id='42')
    so the vuln detail page can render its own status-change history
    without giving non-admins the full firehose.
    """
    is_admin = current_user.role == UserRole.ADMIN
    is_scoped_resource = resource_type and resource_id
    if not is_admin and not is_scoped_resource:
        raise HTTPException(
            status_code=403,
            detail="Not authorized to view audit logs without a resource scope",
        )

    query = db.query(AuditLog)

    if user_id:
        query = query.filter(AuditLog.user_id == user_id)
    if resource_type:
        query = query.filter(AuditLog.resource_type == resource_type)
    if resource_id:
        query = query.filter(AuditLog.resource_id == resource_id)

    logs = query.order_by(desc(AuditLog.timestamp)).offset(skip).limit(limit).all()

    response = []
    for log in logs:
        response.append({
            "id": log.id,
            "user_id": log.user_id,
            "username": log.user.username if log.user else "System/Auto",
            "event_type": log.event_type.value if hasattr(log.event_type, 'value') else str(log.event_type),
            "event_description": log.event_description,
            "ip_address": log.ip_address,
            "resource_type": log.resource_type,
            "resource_id": log.resource_id,
            "old_value": log.old_value,
            "new_value": log.new_value,
            "timestamp": log.timestamp
        })

    return response
