from sqlalchemy import func
from core.exceptions import ErrorCollector
from .. import models
from sqlalchemy.orm import Session


def item_exists(db: Session, item_line: int, tenant_id: int, company_id: int):
    item_exists = (
        db.query(models.LineItem)
        .filter(
            models.LineItem.line_number == item_line,
            models.LineItem.tenant_id == tenant_id,
            models.LineItem.company_id == company_id,
        )
        .first()
    )

    return item_exists


def count_items(db: Session, invoice_id: int, tenant_id: int, company_id: int):
    count = (
        db.query(func.count())
        .select_from(models.LineItem)
        .filter(
            models.LineItem.invoice_id == invoice_id,
            models.LineItem.tenant_id == tenant_id,
            models.LineItem.company_id == company_id,
        )
        .scalar()
    )

    return count
