from fastapi import APIRouter, Depends, HTTPException, Query, Path
from typing import Optional, List
from app.db import database
from app.v1.dependencies.auth import get_current_userdetails
from app.v1.models.saas.auditmodel import AuditLog, AuditLogCreate
from app.v1.services.saas.audit import (
    create_audit_log_service,
    list_audit_logs_service,
    list_global_audit_logs_service
)

router = APIRouter()

@router.post("/", response_model=AuditLog)
async def create_audit_log(
    audit_log: AuditLogCreate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Create a new audit log record.
    Typically called internally after user actions.
    """
    try:
        new_log = await create_audit_log_service(audit_log, db)
        return new_log
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Audit log creation failed: {str(e)}")

@router.get("/", response_model=List[AuditLog])
async def list_audit_logs(
    skip: int = Query(0, ge=0),
    limit: int = Query(10, ge=1),
    account_id: Optional[str] = Query(None, description="Filter logs by account_id"),
    user_id: Optional[str] = Query(None, description="Filter logs by user_id"),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Retrieve a paginated list of audit logs.
    If filters are provided (account_id or user_id), returns filtered logs;
    otherwise, returns all (global) audit logs.
    """
    try:
        if account_id or user_id:
            logs = await list_audit_logs_service(skip, limit, account_id, user_id, db)
        else:
            logs = await list_global_audit_logs_service(skip, limit, db)
        return logs
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to list audit logs: {str(e)}")
