from typing import Any

from django.conf import settings
from django.core.checks import Error, Warning

from vq_django_auth.app_settings import api_settings
from vq_django_auth.choices import AuthMethod


def auth_security_check(**kwargs: Any) -> list[Warning]:
    """
    Run security checks for the vq-django-auth configuration.

    Returns:
        List of Error objects for any security issues found
    """

    warnings = []

    # Check for password validation settings
    if (
        not hasattr(settings, "AUTH_PASSWORD_VALIDATORS")
        or not settings.AUTH_PASSWORD_VALIDATORS
    ):
        warnings.append(
            Warning(
                "No password validators configured.",
                hint="Define AUTH_PASSWORD_VALIDATORS in your Django settings.",
                id="vq_django_auth.W002",
            )
        )

    return warnings


def auth_compatibility_check(**kwargs: Any) -> list[Error]:
    """
    Run compatibility checks for the vq-django-auth configuration.

    Returns:
        List of Error objects for any compatibility issues found
    """

    errors = []

    # Check for dependencies in INSTALLED_APPS
    required_apps = []

    if api_settings.AUTH_METHOD is None:
        return [
            Error(
                "AUTH_METHOD need to be set",
                hint=f"See README. Here current options: {AuthMethod}",
                id="vq_django_auth.E001",
            )
        ]

    try:
        AuthMethod(api_settings.AUTH_METHOD)
    except ValueError:
        return [
            Error(
                f"AUTH_METHOD value need to be in {AuthMethod}",
                hint=f"See README. Here current options: {AuthMethod}",
                id="vq_django_auth.E002",
            )
        ]

    # Check for token auth

    # TODO: Check DEFAULT_AUTHENTICATION_CLASSES
    if (
        api_settings.AUTH_METHOD is AuthMethod.TOKEN
        and "rest_framework.authtoken" not in settings.INSTALLED_APPS
    ):
        required_apps.append("rest_framework.authtoken")

    if required_apps:
        errors.append(
            Error(
                f"Missing required apps in INSTALLED_APPS: {', '.join(required_apps)}",
                hint=f"Add {', '.join(required_apps)} to INSTALLED_APPS in your Django settings.",
                id="vq_django_auth.E003",
            )
        )

    return errors


def front_url_is_set(**kwargs: Any) -> list[Warning]:
    warnings = []

    if (
        api_settings.PASSWORD_RESET_SEND_MAIL
        == "vq_django_auth.usecases.send_password_reset_email"
        and api_settings.FRONT_RESET_PASSWORD_PATH is None
    ):
        warnings.append(
            Warning(
                "No 'FRONT_RESET_PASSWORD_PATH'",
                hint="'FRONT_RESET_PASSWORD_PATH' should be set to a valid URL or you need to implement your own email function via 'PASSWORD_RESET_SEND_MAIL'",
                id="vq_django_auth.W003",
            )
        )

    return warnings
