"""
Django views for Lark integration.
"""

import lark
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseBadRequest, HttpResponseRedirect
from django.views.decorators.http import require_http_methods

from .client import get_lark_client
from .utils import get_external_id_for_user


@login_required
@require_http_methods(["GET"])
def customer_portal_redirect(request):
    """
    Redirect user to their Lark customer portal.

    Creates a portal session and redirects to the portal URL.
    Uses the user's external_id to identify them in Lark.

    Query params:
        return_url: Optional URL to return to after portal visit.
    """
    user = request.user
    return_url = request.GET.get("return_url", request.build_absolute_uri("/"))
    external_id = get_external_id_for_user(user)

    try:
        client = get_lark_client()
        session = client.customer_portal.create_session(
            subject_id=external_id,  # Lark accepts external_id here
            return_url=return_url,
        )
        return HttpResponseRedirect(session.url)
    except lark.APIError as e:
        return HttpResponseBadRequest(f"Unable to create portal session: {e}")
