"""Approval repository (tenant-scoped)."""

from __future__ import annotations

import uuid

from sqlalchemy import select
from sqlalchemy.orm import Session

from legate.agent.enums import ApprovalStatus
from legate.db.models.approval import Approval


def get(db: Session, *, workspace_id: uuid.UUID, approval_id: uuid.UUID) -> Approval | None:
    return db.scalars(
        select(Approval).where(Approval.id == approval_id, Approval.workspace_id == workspace_id)
    ).first()


def list_for_workspace(
    db: Session,
    *,
    workspace_id: uuid.UUID,
    status: ApprovalStatus | None = None,
    limit: int = 100,
    offset: int = 0,
) -> list[Approval]:
    stmt = select(Approval).where(Approval.workspace_id == workspace_id)
    if status is not None:
        stmt = stmt.where(Approval.status == status)
    stmt = stmt.order_by(Approval.created_at.desc()).limit(limit).offset(offset)
    return list(db.scalars(stmt).all())
