"""
Preferences API - user settings
"""

import os
import uuid
import flask
import jwt
import core.auth as auth
import core.postgres as postgres


def _get_user_uuid(token):
    try:
        payload = jwt.decode(token, os.getenv("JWT_SECRET"), algorithms=["HS256"])
        return payload.get("sub")
    except (jwt.ExpiredSignatureError, jwt.InvalidTokenError):
        return None


def _auth(request):
    header = request.headers.get("Authorization", "")
    if not header.startswith("Bearer "):
        return None
    token = header[7:]
    user_uuid = _get_user_uuid(token)
    if not user_uuid or not auth.verifyLoginToken(token, userUUID=user_uuid):
        return None
    return user_uuid


def register(app):

    @app.route("/api/preferences", methods=["GET"])
    def api_getPreferences():
        """Get user preferences."""
        user_uuid = _auth(flask.request)
        if not user_uuid:
            return flask.jsonify({"error": "unauthorized"}), 401
        prefs = postgres.select_one("user_preferences", {"user_uuid": user_uuid})
        if not prefs:
            # Return defaults
            return flask.jsonify({
                "sound_enabled": False,
                "haptic_enabled": True,
                "show_launch_screen": True,
                "celebration_style": "standard",
            }), 200
        return flask.jsonify(prefs), 200

    @app.route("/api/preferences", methods=["PUT"])
    def api_updatePreferences():
        """Update user preferences."""
        user_uuid = _auth(flask.request)
        if not user_uuid:
            return flask.jsonify({"error": "unauthorized"}), 401
        data = flask.request.get_json()
        if not data:
            return flask.jsonify({"error": "missing body"}), 400

        allowed = ["sound_enabled", "haptic_enabled", "show_launch_screen", "celebration_style", "timezone_offset"]
        updates = {k: v for k, v in data.items() if k in allowed}
        if not updates:
            return flask.jsonify({"error": "no valid fields"}), 400

        existing = postgres.select_one("user_preferences", {"user_uuid": user_uuid})
        if existing:
            result = postgres.update("user_preferences", updates, {"user_uuid": user_uuid})
            return flask.jsonify(result[0] if result else {}), 200
        else:
            updates["id"] = str(uuid.uuid4())
            updates["user_uuid"] = user_uuid
            result = postgres.insert("user_preferences", updates)
            return flask.jsonify(result), 201
