import pytest
from fastapi import HTTPException

from api.v1.modules.crm.accounts import service
from api.v1.modules.crm.accounts.dto import AccountCreate, AccountUpdate

T, C = 1, 1


def test_create_and_get_account(db):
    acc = service.create_account(
        db,
        AccountCreate(name="Importadora Demo", rfc="XAXX010101000", account_type="importador"),
        T, C,
    )
    assert acc.id is not None
    assert acc.status == "active"
    assert acc.country == "MEX"  # ISO 3166-1 alfa-3 (alineado al catálogo pais)
    got = service.get_account(db, acc.id, T, C)
    assert got.name == "Importadora Demo"
    assert got.rfc == "XAXX010101000"


def test_list_and_search(db):
    service.create_account(db, AccountCreate(name="Alpha SA"), T, C)
    service.create_account(db, AccountCreate(name="Beta SA"), T, C)
    assert len(service.get_accounts(db, T, C)) == 2
    found = service.get_accounts(db, T, C, search="alpha")
    assert len(found) == 1 and found[0].name == "Alpha SA"


def test_filter_by_status(db):
    service.create_account(db, AccountCreate(name="Activa", status="active"), T, C)
    service.create_account(db, AccountCreate(name="Prospecto", status="prospect"), T, C)
    only_prospect = service.get_accounts(db, T, C, account_status="prospect")
    assert len(only_prospect) == 1 and only_prospect[0].name == "Prospecto"


def test_update_account(db):
    acc = service.create_account(db, AccountCreate(name="X"), T, C)
    upd = service.update_account(db, acc.id, AccountUpdate(status="inactive", phone="5551234567"), T, C)
    assert upd.status == "inactive"
    assert upd.phone == "5551234567"


def test_soft_delete_hides_account(db):
    acc = service.create_account(db, AccountCreate(name="Y"), T, C)
    service.delete_account(db, acc.id, T, C)
    with pytest.raises(HTTPException) as exc:
        service.get_account(db, acc.id, T, C)
    assert exc.value.status_code == 404
    assert service.get_accounts(db, T, C) == []


def test_tenant_isolation(db):
    acc = service.create_account(db, AccountCreate(name="Z"), T, C)
    assert service.get_accounts(db, tenant_id=999, company_id=C) == []
    with pytest.raises(HTTPException):
        service.get_account(db, acc.id, 999, C)
