from decimal import Decimal
from sqlalchemy.orm import Session
from api.v1.modules.a76.general_catalogs.unit_conversions.models import UnitConversion

def _get_unit_equivalence(
    db: Session,
    from_unit: str,
    to_unit: str,
    tenant_id: str,
    company_id: str,
) -> tuple[str, Decimal]:
    """
    Busca una conversión entre dos unidades de medida.
    Paridad: REVEQUIVALENCIA (Clarion SCAII).

    Retorna (multi_divide, factor_conv):
      - ('M', factor) → multiplicar cantidad por factor
      - ('D', factor) → dividir cantidad por factor
      - ('',  0)      → no existe equivalencia
    """
    conv = (
        db.query(UnitConversion)
        .filter(
            UnitConversion.tenant_id == tenant_id,
            UnitConversion.company_id == company_id,
            UnitConversion.from_unit_code == from_unit,
            UnitConversion.to_unit_code == to_unit,
        )
        .first()
    )
    if conv and conv.conversion_factor:
        return "M", conv.conversion_factor

    conv_inv = (
        db.query(UnitConversion)
        .filter(
            UnitConversion.tenant_id == tenant_id,
            UnitConversion.company_id == company_id,
            UnitConversion.from_unit_code == to_unit,
            UnitConversion.to_unit_code == from_unit,
        )
        .first()
    )
    if conv_inv and conv_inv.conversion_factor:
        return "D", conv_inv.conversion_factor

    return "", Decimal(0)
