import pytest
from auth.factories import UserFactory
from auth.services import (
    AuthService,
    SignupUserDTO,
    UserService,
    LoginUserDTO,
    InvalidEmailError,
    InvalidPasswordError,
)
from tests.integrations import TestMailClient


async def test_auth_signup(
    auth_service: AuthService, mail_client: TestMailClient, user_service: UserService
):
    user = UserFactory.build()
    signup_user = await auth_service.signup(
        SignupUserDTO(
            email=user.email,
            password=user.password,
        )
    )
    assert mail_client.messages == [([signup_user.email], "Sign up", "sign up info code")]

    created_user = await user_service.get(signup_user.id)
    assert created_user.email == signup_user.email

    # teardown
    await auth_service.user_service.delete(signup_user.id)


async def test_auth_login_success(auth_service: AuthService):
    user = UserFactory.build()
    signup_user = await auth_service.signup(
        SignupUserDTO(
            email=user.email,
            password=user.password,
        )
    )

    token = await auth_service.login(
        LoginUserDTO(
            email=user.email,
            password=user.password,
        )
    )
    account = await auth_service.get_account(token)

    assert account.email == user.email
    await auth_service.user_service.delete(signup_user.id)


async def test_auth_login_wrong_email(auth_service: AuthService):
    user = UserFactory.build()
    signup_user = await auth_service.signup(
        SignupUserDTO(
            email=user.email,
            password=user.password,
        )
    )

    with pytest.raises(InvalidEmailError):
        await auth_service.login(
            LoginUserDTO(
                email="wrong@mail.com",
                password=user.password,
            )
        )
    await auth_service.user_service.delete(signup_user.id)


async def test_auth_login_wrong_password(auth_service: AuthService):
    user = UserFactory.build()
    signup_user = await auth_service.signup(
        SignupUserDTO(
            email=user.email,
            password=user.password,
        )
    )

    with pytest.raises(InvalidPasswordError):
        await auth_service.login(
            LoginUserDTO(
                email=user.email,
                password="wrong_password",
            )
        )
    await auth_service.user_service.delete(signup_user.id)
