import pytest
from fastapi import HTTPException

from api.v1.modules.crm.accounts import service as accounts_service
from api.v1.modules.crm.accounts.dto import AccountCreate
from api.v1.modules.crm.addresses import service
from api.v1.modules.crm.addresses.dto import AddressCreate
from api.v1.modules.crm.suppliers import service as suppliers_service
from api.v1.modules.crm.suppliers.dto import SupplierCreate

T, C = 1, 1


def test_address_requires_exactly_one_owner(db):
    # Ni cliente ni proveedor
    with pytest.raises(HTTPException) as exc:
        service.create_address(db, AddressCreate(address_type="fiscal"), T, C)
    assert exc.value.status_code == 422


def test_address_rejects_both_owners(db):
    acc = accounts_service.create_account(db, AccountCreate(name="Cli"), T, C)
    sup = suppliers_service.create_supplier(db, SupplierCreate(name="Prov"), T, C)
    with pytest.raises(HTTPException) as exc:
        service.create_address(db, AddressCreate(account_id=acc.id, supplier_id=sup.id), T, C)
    assert exc.value.status_code == 422


def test_create_and_list_addresses_for_account(db):
    acc = accounts_service.create_account(db, AccountCreate(name="Cli"), T, C)
    service.create_address(db, AddressCreate(account_id=acc.id, address_type="fiscal", street="Av. Reforma", postal_code="06600", is_primary=True), T, C)
    service.create_address(db, AddressCreate(account_id=acc.id, address_type="bodega", city="Tijuana"), T, C)
    addrs = service.get_addresses(db, T, C, account_id=acc.id)
    assert len(addrs) == 2
    assert addrs[0].is_primary is True  # el principal va primero


def test_address_rejects_unknown_owner(db):
    with pytest.raises(HTTPException) as exc:
        service.create_address(db, AddressCreate(account_id=999, address_type="fiscal"), T, C)
    assert exc.value.status_code == 422
