"""Pruebas del generador de folios del ciclo comercial (next_folio)."""

from datetime import date

from api.v1.modules.crm.common.folios import next_folio

T, C = 1, 1


def test_folio_format_and_direction(db):
    folio = next_folio(db, T, C, "O", "exportacion", on_date=date(2025, 8, 15))
    assert folio == "O2025-08-001-E"
    imp = next_folio(db, T, C, "S", "importacion", on_date=date(2025, 8, 15))
    assert imp == "S2025-08-001-I"
    sin_dir = next_folio(db, T, C, "C", None, on_date=date(2025, 8, 15))
    assert sin_dir == "C2025-08-001-X"


def test_folio_monthly_consecutive_per_entity(db):
    a = next_folio(db, T, C, "O", "exportacion", on_date=date(2025, 8, 1))
    b = next_folio(db, T, C, "O", "exportacion", on_date=date(2025, 8, 20))
    assert a == "O2025-08-001-E"
    assert b == "O2025-08-002-E"  # mismo mes, mismo entity → +1


def test_folio_resets_on_month_change(db):
    next_folio(db, T, C, "O", "exportacion", on_date=date(2025, 8, 20))
    sep = next_folio(db, T, C, "O", "exportacion", on_date=date(2025, 9, 1))
    assert sep == "O2025-09-001-E"  # nuevo mes → reinicia consecutivo


def test_folio_entities_do_not_share_counter(db):
    o = next_folio(db, T, C, "O", "exportacion", on_date=date(2025, 8, 20))
    s = next_folio(db, T, C, "S", "exportacion", on_date=date(2025, 8, 20))
    op = next_folio(db, T, C, "OP", "importacion", on_date=date(2025, 8, 20))
    assert o == "O2025-08-001-E"
    assert s == "S2025-08-001-E"   # entity distinto → su propio consecutivo
    assert op == "OP2025-08-001-I"


def test_folio_invoice_without_direction(db):
    # Facturas: entidad F sin sufijo de dirección (F2025-08-001)
    folio = next_folio(db, T, C, "F", None, on_date=date(2025, 8, 3), with_direction=False)
    assert folio == "F2025-08-001"


def test_folio_unique_across_many(db):
    folios = {next_folio(db, T, C, "C", "importacion", on_date=date(2025, 8, 10)) for _ in range(25)}
    assert len(folios) == 25  # sin duplicados
