import pytest
from fastapi import HTTPException

from api.v1.modules.crm.suppliers import service
from api.v1.modules.crm.suppliers.dto import SupplierCreate, SupplierUpdate

T, C = 1, 1


def test_create_supplier_with_multivalue_fields(db):
    supplier = service.create_supplier(
        db,
        SupplierCreate(
            name="Naviera del Golfo SA",
            classifications=["naviera", "agente_carga"],
            coverage="internacional",
            countries=["MX", "US", "PA"],
            ports=["Veracruz", "Manzanillo"],
            customs=["Veracruz"],
            quote_currency="USD",
        ),
        T, C, user_id="dev",
    )
    assert supplier.id is not None
    assert supplier.status == "active"
    assert supplier.classifications == ["naviera", "agente_carga"]
    assert supplier.countries == ["MX", "US", "PA"]
    assert supplier.created_by == "dev"


def test_list_and_search_supplier(db):
    service.create_supplier(db, SupplierCreate(name="Aerolínea Carga MX", classifications=["aerolinea"]), T, C)
    service.create_supplier(db, SupplierCreate(name="Transportes Terrestres"), T, C)
    assert len(service.get_suppliers(db, T, C)) == 2
    found = service.get_suppliers(db, T, C, search="aero")
    assert len(found) == 1 and found[0].name == "Aerolínea Carga MX"


def test_update_supplier_replaces_lists(db):
    s = service.create_supplier(db, SupplierCreate(name="X", classifications=["naviera"]), T, C)
    upd = service.update_supplier(db, s.id, SupplierUpdate(classifications=["ferrocarril", "almacen"]), T, C)
    assert upd.classifications == ["ferrocarril", "almacen"]


def test_soft_delete_supplier(db):
    s = service.create_supplier(db, SupplierCreate(name="Y"), T, C)
    service.delete_supplier(db, s.id, T, C)
    with pytest.raises(HTTPException) as exc:
        service.get_supplier(db, s.id, T, C)
    assert exc.value.status_code == 404
    assert service.get_suppliers(db, T, C) == []
