from decimal import Decimal

from api.v1.modules.a24.balance_movements.models import BalanceMovement, MovementType
from api.v1.modules.a76.invoices.imports.process import main_process as import_main
from tests.fixtures.builders import (
    create_business_catalogs,
    create_import_invoice_with_line,
    ensure_reference_data,
)


def _patch_import_pipeline(monkeypatch, import_line):
    monkeypatch.setattr(import_main, "pre_validators", lambda *args, **kwargs: [import_line])
    monkeypatch.setattr(import_main, "review_classes", lambda *args, **kwargs: None)
    monkeypatch.setattr(import_main, "review_exchange_rate", lambda *args, **kwargs: None)
    monkeypatch.setattr(import_main, "review_weights_kgs", lambda *args, **kwargs: None)
    monkeypatch.setattr(import_main, "review_weights_lbs", lambda *args, **kwargs: None)
    monkeypatch.setattr(import_main, "_validate_sisimp_limits", lambda *args, **kwargs: None)
    monkeypatch.setattr(import_main, "_validate_lines", lambda *args, **kwargs: ([], {}))


def test_process_import_endpoint_creates_balance_entries(client, db_session, monkeypatch, test_tenant):
    tid, cid = test_tenant.tenant_id, test_tenant.company_id
    ensure_reference_data(db_session)
    catalogs = create_business_catalogs(db_session, tenant_id=tid, company_id=cid)
    invoice, line = create_import_invoice_with_line(
        db_session, tid, cid, catalogs, invoice_type="TEM", invoice_number="IMP-INT-01", qty=Decimal("7")
    )
    _patch_import_pipeline(monkeypatch, line)

    resp = client.post(f"/api/v1/a76/invoices/{invoice.id}/process?company_id={cid}")
    assert resp.status_code == 200

    entries = (
        db_session.query(BalanceMovement)
        .filter(
            BalanceMovement.import_invoice_id == invoice.id,
            BalanceMovement.import_item_line_id == line.id,
            BalanceMovement.movement_type == MovementType.ENTRY,
        )
        .all()
    )
    assert len(entries) >= 1


def test_process_import_def_does_not_create_balance_entries(client, db_session, monkeypatch, test_tenant):
    tid, cid = test_tenant.tenant_id, test_tenant.company_id
    ensure_reference_data(db_session)
    catalogs = create_business_catalogs(db_session, tenant_id=tid, company_id=cid)
    invoice, line = create_import_invoice_with_line(
        db_session, tid, cid, catalogs, invoice_type="DEF", invoice_number="IMP-DEF-01", qty=Decimal("7")
    )
    _patch_import_pipeline(monkeypatch, line)

    resp = client.post(f"/api/v1/a76/invoices/{invoice.id}/process?company_id={cid}")
    assert resp.status_code == 200

    entries = (
        db_session.query(BalanceMovement)
        .filter(BalanceMovement.import_invoice_id == invoice.id)
        .all()
    )
    assert entries == []
