"""
Platform Gateway — Response helpers mixed into GatewayHandler.
"""

import json
from http.cookies import SimpleCookie

from config import SESSION_MAX_AGE, DEV_AUTO_LOGIN
from sessions import get_session_user, get_or_create_dev_user


class ResponseMixin:
    """Mixin providing response helpers for GatewayHandler."""

    def _send_json(self, data, status=200):
        body = json.dumps(data).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", len(body))
        self.end_headers()
        self.wfile.write(body)

    def _get_session_token(self):
        cookie = SimpleCookie(self.headers.get("Cookie", ""))
        if "platform_session" in cookie:
            return cookie["platform_session"].value
        auth = self.headers.get("Authorization", "")
        if auth.startswith("Bearer "):
            return auth[7:]
        return None

    def _get_user(self):
        if DEV_AUTO_LOGIN and self.headers.get("X-Dev-Auto-Login") == "1":
            return get_or_create_dev_user()
        token = self._get_session_token()
        return get_session_user(token)

    def _require_auth(self):
        user = self._get_user()
        if not user:
            self._send_json({"error": "Unauthorized"}, 401)
            return None
        return user

    def _set_session_cookie(self, token):
        self.send_header("Set-Cookie",
                         f"platform_session={token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age={SESSION_MAX_AGE}")

    def _read_body(self):
        length = int(self.headers.get("Content-Length", 0))
        return self.rfile.read(length) if length > 0 else b""
