from django.conf import settings
from django.core.checks import ERROR, WARNING, CheckMessage, register


@register()
def check_servala_settings(app_configs, **kwargs):
    """Checks all settings that should be present in all environments."""
    if app_configs:
        # Don’t run if we’re meant to only test individual apps
        return []

    errors = []
    required_fields = ("URL", "DB", "USERNAME", "PASSWORD")
    missing_fields = [
        field for field in required_fields if not settings.ODOO.get(field)
    ]
    if missing_fields:
        fields = ", ".join(missing_fields)
        errors.append(
            CheckMessage(
                level=WARNING if settings.DEBUG else ERROR,
                msg=f"Missing Odoo config: {fields}",
                hint="Make sure you set the required SERVALA_ODOO_* settings.",
                id="servala.E001",
            )
        )
    oidc_config = settings.SOCIALACCOUNT_PROVIDERS["openid_connect"]["APPS"][0]
    missing_fields = [
        field for field in ("client_id", "secret") if not oidc_config.get(field)
    ]
    if not oidc_config["settings"]["server_url"]:
        missing_fields.append("server_url")
    if missing_fields:
        fields = ", ".join(
            [f"SERVALA_KEYCLOAK_{field.upper()}" for field in missing_fields]
        )
        errors.append(
            CheckMessage(
                level=WARNING if settings.DEBUG else ERROR,
                msg=f"Missing Keycloak config: {fields}",
                id="servala.E002",
            )
        )

    if settings.SERVALA_ENVIRONMENT not in ("development", "staging", "production"):
        errors.append(
            CheckMessage(
                level=ERROR,
                msg=f"Invalid environment {settings.SERVALA_ENVIRONMENT}",
                hint="Must be one of development, staging, production.",
                id="servala.E003",
            )
        )

    return errors


@register(deploy=True)
def check_servala_production_settings(app_configs, **kwargs):
    if app_configs:
        # Don’t run if we’re meant to only test individual apps
        return []

    errors = []
    if settings.SERVALA_ENVIRONMENT == "development":
        errors.append(
            CheckMessage(
                level=ERROR,
                msg="Environment is set to 'development'.",
                id="servala.E004",
            )
        )
    if "insecure" in settings.SECRET_KEY:
        errors.append(
            CheckMessage(
                level=ERROR, msg="Secret key contains 'insecure'.", id="servala.E005"
            )
        )
    if settings.EMAIL_USE_SSL and settings.EMAIL_USE_TLS:
        errors.append(
            CheckMessage(
                level=WARNING,
                msg="Use either SSL or TLS in email config, not both!",
                id="servala.W001",
            )
        )

    return errors
