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.contacts import service
from api.v1.modules.crm.contacts.dto import ContactCreate

T, C = 1, 1


def test_create_contact_rejects_unknown_account(db):
    with pytest.raises(HTTPException) as exc:
        service.create_contact(db, ContactCreate(first_name="Juan", account_id=999), T, C)
    assert exc.value.status_code == 422


def test_create_and_list_by_account(db):
    acc = accounts_service.create_account(db, AccountCreate(name="Empresa"), T, C)
    contact = service.create_contact(
        db,
        ContactCreate(first_name="Ana", last_name="López", account_id=acc.id, is_primary=True),
        T, C,
    )
    assert contact.account_id == acc.id
    assert contact.is_primary is True
    listed = service.get_contacts(db, T, C, account_id=acc.id)
    assert len(listed) == 1 and listed[0].first_name == "Ana"


def test_contact_without_account_is_allowed(db):
    contact = service.create_contact(db, ContactCreate(first_name="Suelto"), T, C)
    assert contact.account_id is None
