from sqlalchemy.orm import Session

from api.v1.modules.a76.general_catalogs.exchange_rate.models import ExchangeRate
from core.exceptions import ErrorCollector
from ...schemas import InvoiceHeaderCreate
from ...common.common_validators import validate_common, validate_required_fields_by_operation

def validate_create(db: Session, invoice: InvoiceHeaderCreate, tenant_id: int, company_id: int, errors: ErrorCollector) -> None:
    """ Valida la creación de una nueva factura de importe temporal """
    
    if not invoice.operation_type:
        errors.add_required_error("operation_type")
        
    if not invoice.invoice_type:
        errors.add_required_error("invoice_type")
        
    if not invoice.document_type and invoice.invoice_type != "MEX":
        errors.add_required_error("document_type")
    
    if not invoice.invoice_number:
        errors.add_required_error("invoice_number")
    
    if not invoice.invoice_date:
        errors.add_required_error("invoice_date")
    
    # Validar campos obligatorios según tipo de operación
    invoice_data = {
        'provider_header': invoice.compliance_mx.provider_header if invoice.compliance_mx else None,
        'provider_id': invoice.compliance_mx.provider_id if invoice.compliance_mx else None,
        'sold_to_header': invoice.compliance_mx.sold_to_header if invoice.compliance_mx else None,
        'sold_to_id': invoice.compliance_mx.sold_to_id if invoice.compliance_mx else None,        
        'shipped_to_header': invoice.compliance_mx.shipped_to_header if invoice.compliance_mx else None,
        'shipped_to_id': invoice.compliance_mx.shipped_to_id if invoice.compliance_mx else None,
        'customs_broker_id': invoice.compliance_mx.customs_broker_id if invoice.compliance_mx else None,
        'pedimento_id': invoice.compliance_mx.pedimento_id if invoice.compliance_mx else None,
    }
    
    validate_required_fields_by_operation(
        invoice_data=invoice_data,
        operation_type=invoice.operation_type,
        errors=errors
    )
    
    if errors.has_errors():
        """Se retorna porque hay campos obligatorios según el tipo de operación que deben ser llenados"""
        return
    
    validate_common(db, invoice, tenant_id, company_id, errors)
    
    if errors.has_errors():
        """Se retorna por que fallaron las validaciones generales"""
        return
        
    if invoice.compliance_mx:
        if not invoice.compliance_mx.pedimento_id:
            invoice.compliance_mx.remesa = None        
        
    if invoice.financials:
        if not invoice.financials.exchange_rate:
            invoice.financials.exchange_rate = db.query(ExchangeRate.value).filter(ExchangeRate.date == invoice.invoice_date).scalar()
            
    invoice.document_type = (invoice.document_type or "").upper()
       
    if invoice.logistics:
        if not invoice.logistics.transport_type:
            invoice.logistics.transport_type = "none"
                
        if invoice.logistics.transport_type == "none" and invoice.logistics.transport_num:
            invoice.logistics.transport_num = None
        
        invoice.logistics.incoterm = (invoice.logistics.incoterm or "").upper()
        
        if not invoice.logistics.weight_type:
            invoice.logistics.weight_type = "kgs"    

    if invoice.financials:
        if not invoice.financials.currency:
            invoice.financials.currency = "foreign"
           
        if invoice.financials.currency == "local":
            invoice.financials.currency_type = "MXN"
        elif invoice.financials.currency == "foreign":
            invoice.financials.currency_type = "USD"    
        elif invoice.financials.currency == "manual":        
            invoice.financials.currency_type = (invoice.financials.currency_type or "").upper()