"""Tests for usuarios schemas."""

from __future__ import annotations

import pytest

pytest.importorskip("email_validator")

from src.modules.usuarios.schemas import UsuarioCreate, UsuarioOut, UsuarioUpdate


def test_usuario_create_accepts_full_payload_and_sets_aliases() -> None:
    payload = {
        "identificador": "user@test.com",
        "senha": "plain-password",
        "ativo": True,
        "superadmin": False,
        "auth-id-appwrite": "appwrite_user_1",
        "nome": "Usuário Teste",
        "email": "user@test.com",
        "telefone": "11987654321",
        "nivel": "admin",
        "registro-completo": True,
        "enderecos": ["endereco_1", "endereco_2"],
        "empresasDados": ["empresa_1"],
        "nome-social": "Teste",
        "cpf": "12345678901",
    }

    model = UsuarioCreate.model_validate(payload)
    dumped = model.model_dump(by_alias=True)

    assert dumped == {
        "identificador": "user@test.com",
        "senha": "plain-password",
        "ativo": True,
        "superadmin": False,
        "auth-id-appwrite": "appwrite_user_1",
        "nome": "Usuário Teste",
        "email": "user@test.com",
        "telefone": "11987654321",
        "nivel": "admin",
        "registro-completo": True,
        "enderecos": ["endereco_1", "endereco_2"],
        "empresasDados": ["empresa_1"],
        "nome-social": "Teste",
        "cpf": "12345678901",
    }


def test_usuario_create_defaults_are_applied() -> None:
    model = UsuarioCreate.model_validate({
        "identificador": "user@test.com",
        "senha": "plain-password",
    })

    assert model.ativo is True
    assert model.superadmin is False
    assert model.registro_completo is False
    assert model.enderecos == []
    assert model.empresas_dados == []


def test_usuario_update_uses_aliases_and_optional_fields() -> None:
    payload = {
        "identificador": "novo@test.com",
        "registro-completo": False,
        "empresasDados": ["empresa_1", "empresa_2"],
        "nome-social": "Novo Nome",
        "telefone": "11987654321",
    }

    model = UsuarioUpdate.model_validate(payload)
    dumped = model.model_dump(exclude_unset=True, by_alias=True)

    assert dumped == {
        "identificador": "novo@test.com",
        "registro-completo": False,
        "empresasDados": ["empresa_1", "empresa_2"],
        "nome-social": "Novo Nome",
        "telefone": "11987654321",
    }


def test_usuario_out_does_not_expose_password_field() -> None:
    payload = {
        "id": "user_1",
        "identificador": "user@test.com",
        "senha": "hashed-value",
        "ativo": True,
        "superadmin": False,
        "createdAt": "2025-10-02T19:38:10.336+00:00",
        "updatedAt": "2025-10-09T13:57:07.833+00:00",
    }

    model = UsuarioOut.model_validate(payload)

    with pytest.raises(AttributeError):
        getattr(model, "senha")

    dumped = model.model_dump()
    assert "senha" not in dumped
