"""Server-side error reporting that never shows internals to the client.

Use for UNEXPECTED exceptions only (database/IO/SMTP/network failures, bugs). Deliberate validation / domain errors keep their own,
user-facing messages. The client gets a generic message plus the `request_id` of the failing request; the exception itself (type,
text, traceback) goes to the application error log together with that id, so support can correlate the two.
"""
from flask import current_app, g, has_request_context

GENERIC_MESSAGE = 'Wystąpił błąd serwera.'


def current_request_id():
    return getattr(g, 'request_id', '-') if has_request_context() else '-'


def log_internal_error(context, exc):
    """Log the exception with its traceback and the request id; returns the request id."""
    request_id = current_request_id()
    current_app.logger.error('%s [request_id=%s]: %r', context, request_id, exc, exc_info=(type(exc), exc, exc.__traceback__))
    return request_id


def internal_error_payload(context, exc, message=GENERIC_MESSAGE, **extra):
    """Dict for a JSON error response: a generic `message` (default: GENERIC_MESSAGE) under the `error` key, plus `request_id` and extras."""
    request_id = log_internal_error(context, exc)
    return {'error': message, 'request_id': request_id, **extra}
