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.documents import service
from api.v1.modules.crm.documents.dto import DocumentCreate
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_create_document_for_supplier(db):
    sup = suppliers_service.create_supplier(db, SupplierCreate(name="Prov"), T, C)
    doc = service.create_document(
        db,
        DocumentCreate(supplier_id=sup.id, doc_type="constancia_fiscal",
                       name="Constancia SF 2026", file_url="https://ejemplo.mx/csf.pdf"),
        T, C, user_id="dev",
    )
    assert doc.id is not None
    assert doc.uploaded_by == "dev"
    assert service.get_documents(db, T, C, supplier_id=sup.id)[0].name == "Constancia SF 2026"


def test_create_document_for_account(db):
    acc = accounts_service.create_account(db, AccountCreate(name="Cli"), T, C)
    doc = service.create_document(
        db, DocumentCreate(account_id=acc.id, doc_type="acta_constitutiva", name="Acta"), T, C
    )
    assert doc.account_id == acc.id


def test_document_requires_one_owner(db):
    with pytest.raises(HTTPException) as exc:
        service.create_document(db, DocumentCreate(doc_type="otro", name="Suelto"), T, C)
    assert exc.value.status_code == 422
