from typing import Optional
from core.exceptions import ErrorCollector
from .. import models
from sqlalchemy.orm import Session


def invoice_exists(
    db: Session,
    invoice_number: str,
    tenant_id: int,
    company_id: int,
    errors: Optional[ErrorCollector],
):
    invoice = (
        db.query(models.InvoiceHeader)
        .filter(
            models.InvoiceHeader.invoice_number == invoice_number,
            models.InvoiceHeader.tenant_id == tenant_id,
            models.InvoiceHeader.company_id == company_id,
        )
        .first()
    )

    if invoice:
        if errors:
            errors.add_duplicate_error(
                "invoice_number",
                invoice_number,
                f"Ya existe una factura con el número '{invoice_number}'",
            )
        return invoice
    return None

def invoice_exists_by_id(
    db: Session,
    invoice_id: str,
    tenant_id: int,
    company_id: int,
    errors: Optional[ErrorCollector],
):
    invoice = (
        db.query(models.InvoiceHeader)
        .filter(
            models.InvoiceHeader.id == invoice_id,
            models.InvoiceHeader.tenant_id == tenant_id,
            models.InvoiceHeader.company_id == company_id,
        )
        .first()
    )

    if invoice:
        if errors:
            errors.add_duplicate_error(
                "invoice_id",
                invoice_id,
                f"Ya existe una factura con el número '{invoice_id}'",
            )
        return invoice
    return None


def invoice_updated(
    db: Session,
    invoice_id: str,
    tenant_id: int,
    company_id: int,
    errors: ErrorCollector,
) -> bool:
    is_updated = (
        db.query(models.InvoiceHeader.is_updated)
        .filter(
            models.InvoiceHeader.id == invoice_id,
            models.InvoiceHeader.tenant_id == tenant_id,
            models.InvoiceHeader.company_id == company_id,
        )
        .scalar()
    )

    if is_updated:
        errors.add_error(
            field="invoice_number",
            message=f"La factura con el número '{invoice_id}' ya ha sido actualizada y no se puede modificar.",
            solution="Capturar otro número de Factura de Importación Temporal o Desactualizar la factura.",
            code="INVOICE_UPDATED",
            value=invoice_id,
        )
        return True
    return False
