import os
import sys
from pathlib import Path

import pytest

pytest.importorskip("email_validator")

PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

os.environ.setdefault("APPWRITE_ENDPOINT", "http://localhost/v1")
os.environ.setdefault("APPWRITE_PROJECT_ID", "test-project")
os.environ.setdefault("APPWRITE_API_KEY", "test-key")
os.environ.setdefault("APPWRITE_DATABASE_ID", "test-db")
os.environ.setdefault("APPWRITE_COLLECTION_EMPRESAS_ID", "test-companies")

from src.modules.empresas.schemas import EmpresaUpdate


def test_empresa_update_accepts_formatted_cnpj() -> None:
    payload = {"cnpj": "27.865.757/0001-02"}

    data = EmpresaUpdate(**payload)

    assert data.cnpj == "27865757000102"


def test_empresa_update_accepts_formatted_telefone() -> None:
    payload = {"telefone": "(11) 99876-5432"}

    data = EmpresaUpdate(**payload)

    assert data.telefone == "11998765432"


@pytest.mark.parametrize("value", ["", "123456789", "123456789012345"])
def test_empresa_update_rejects_invalid_telefone(value: str) -> None:
    with pytest.raises(ValueError, match="Telefone must contain 10 or 11 digits including DDD."):
        EmpresaUpdate(telefone=value)


@pytest.mark.parametrize("value", ["", "1234567890123", "123456789012345"])
def test_empresa_update_rejects_invalid_cnpj(value: str) -> None:
    with pytest.raises(ValueError, match="CNPJ must contain exactly 14 numeric characters."):
        EmpresaUpdate(cnpj=value)
