from types import SimpleNamespace

import pytest

from api.v1.modules.a76.general_catalogs.doda.export_service import (
    DodaExportFormat,
    build_export_text,
    doda_row_values,
    parse_export_params,
)


def test_parse_export_params_valid():
    d0, d1, fmt, mode = parse_export_params("2024-01-15", "2024-01-20", "csv", "formatted")
    assert d0 == 20240115
    assert d1 == 20240120
    assert fmt == DodaExportFormat.csv
    assert mode == "formatted"


def test_parse_export_params_rejects_inverted_range():
    with pytest.raises(ValueError, match="date_from"):
        parse_export_params("2024-02-01", "2024-01-01", "csv", "formatted")


def _minimal_row():
    return SimpleNamespace(
        id=1,
        integration_number="INT1",
        doda_date=20240110,
        doda_time=1430,
        dispatch_customs="64",
        customs_sections=None,
        patent="1234",
        pedimentos=None,
        caat=None,
        transport_identification=None,
        fast_id=None,
        operation_type="I",
        responsible=None,
        carrier=None,
        shipments=None,
        pedimento_type=None,
        original_chain=None,
        serial_number=None,
        electronic_signature=None,
        transaction_number=None,
        status="PENDIENTE",
        linq_sat_qr=None,
        sat_certificate=None,
        sat_digital_seal=None,
        xml_doda_sent_path=None,
        xml_doda_response_path=None,
        sat_original_chain=None,
        customs_clearance=None,
        unique_badge_number=None,
        last_user=None,
    )


def test_doda_row_values_length_matches_headers():
    row = _minimal_row()
    assert len(doda_row_values(row, date_mode="formatted")) == 30


def test_build_export_text_includes_header_and_row():
    row = _minimal_row()
    text = build_export_text([row], export_format=DodaExportFormat.csv, date_mode="formatted")
    lines = text.strip().split("\r\n")
    assert "SYSID" in lines[0]
    assert "INT1" in lines[1]
    assert lines[1].startswith("1,")
