from datetime import datetime
from pymongo.collection import Collection, ReturnDocument
from app.db import database
from app.v1.models.saas.auditmodel import AuditLogCreate
from app.v1.libraries.object import str_to_objectid
from typing import Optional, List

COLLECTION_NAME = "audit_logs"

async def create_audit_log_service(audit_log: AuditLogCreate, db: database.MongoDB) -> dict:
    """
    Insert a new audit log record into the audit_logs collection.
    """
    audit_collection: Collection = db[COLLECTION_NAME]
    log_data = audit_log.dict()
    log_data["timestamp"] = datetime.utcnow()
    result = audit_collection.insert_one(log_data)
    log_data["_id"] = str(result.inserted_id)
    log_data["audit_id"] = log_data["_id"]
    return log_data

async def list_audit_logs_service(skip: int, limit: int, account_id: Optional[str], user_id: Optional[str], db: database.MongoDB) -> List[dict]:
    """
    Retrieve a paginated list of audit logs.
    If account_id or user_id is provided, filters are applied; otherwise, global logs are returned.
    """
    audit_collection: Collection = db[COLLECTION_NAME]
    query = {}
    if account_id:
        query["account_id"] = account_id
    if user_id:
        query["user_id"] = user_id
    cursor = audit_collection.find(query).skip(skip).limit(limit).sort("timestamp", -1)
    logs = []
    async for doc in cursor:
        doc["_id"] = str(doc["_id"])
        doc["audit_id"] = doc["_id"]
        logs.append(doc)
    return logs

async def list_global_audit_logs_service(skip: int, limit: int, db: database.MongoDB) -> List[dict]:
    """
    Retrieve a paginated list of all audit logs (global view).
    """
    audit_collection: Collection = db[COLLECTION_NAME]
    cursor = audit_collection.find({}).skip(skip).limit(limit).sort("timestamp", -1)
    logs = []
    async for doc in cursor:
        doc["_id"] = str(doc["_id"])
        doc["audit_id"] = doc["_id"]
        logs.append(doc)
    return logs
