"""
Error Handlers
==============

Custom error handlers for the Flask application.
"""

from flask import render_template, jsonify, request
import logging

logger = logging.getLogger(__name__)


def register_error_handlers(app):
    """Register all error handlers with the app."""

    @app.errorhandler(400)
    def bad_request(e):
        if request.is_json:
            return jsonify({'error': 'Bad request', 'message': str(e)}), 400
        return render_template('errors/400.html'), 400

    @app.errorhandler(403)
    def forbidden(e):
        if request.is_json:
            return jsonify({'error': 'Forbidden', 'message': 'Access denied'}), 403
        return render_template('errors/403.html'), 403

    @app.errorhandler(404)
    def not_found(e):
        if request.is_json:
            return jsonify({'error': 'Not found'}), 404
        return render_template('errors/404.html'), 404

    @app.errorhandler(429)
    def ratelimit_handler(e):
        logger.warning(f"Rate limit exceeded: {request.remote_addr} - {request.path}")
        if request.is_json:
            return jsonify({
                'error': 'Rate limit exceeded',
                'message': 'Zbyt wiele zapytań. Spróbuj ponownie później.'
            }), 429
        return render_template('errors/429.html'), 429

    @app.errorhandler(500)
    def internal_error(e):
        logger.error(f"Internal server error: {e}")
        if request.is_json:
            return jsonify({'error': 'Internal server error'}), 500
        return render_template('errors/500.html'), 500
