from __future__ import annotations

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models.audit_log import AuditLog


class AuditLogRepository:
    def __init__(self, db: Session) -> None:
        self.db = db

    def list(
        self,
        *,
        resource_type: str | None = None,
        resource_id: str | None = None,
        action: str | None = None,
        limit: int = 50,
    ) -> list[AuditLog]:
        stmt = select(AuditLog)
        if resource_type:
            stmt = stmt.where(AuditLog.resource_type == resource_type)
        if resource_id:
            stmt = stmt.where(AuditLog.resource_id == resource_id)
        if action:
            stmt = stmt.where(AuditLog.action == action)
        stmt = stmt.order_by(AuditLog.created_at.desc()).limit(limit)
        return list(self.db.scalars(stmt).all())

    def list_for_resources(
        self,
        *,
        resource_type: str,
        resource_ids: list[str],
        action: str | None = None,
        limit: int | None = None,
    ) -> list[AuditLog]:
        if not resource_ids:
            return []

        stmt = select(AuditLog).where(
            AuditLog.resource_type == resource_type,
            AuditLog.resource_id.in_(resource_ids),
        )
        if action:
            stmt = stmt.where(AuditLog.action == action)
        stmt = stmt.order_by(AuditLog.created_at.desc())
        if limit is not None:
            stmt = stmt.limit(limit)
        return list(self.db.scalars(stmt).all())

    def create(self, log: AuditLog, *, commit: bool = True) -> AuditLog:
        self.db.add(log)
        if commit:
            self.db.commit()
        else:
            self.db.flush()
        self.db.refresh(log)
        return log
