# -*- coding: utf-8 -*-
from __future__ import annotations

import http
import logging

from django.http import HttpRequest, HttpResponse
from django.shortcuts import render

from hotpocket_backend.apps.accounts.decorators import account_required
from hotpocket_backend.apps.ui.services.workflows import CreateSaveWorkflow

LOGGER = logging.getLogger(__name__)


@account_required
def shortcut(request: HttpRequest) -> HttpResponse:
    LOGGER.debug('GET=`%s`', request.GET)

    try:
        assert request.user.is_anonymous is False, 'Login required'
        assert 'url' in request.GET, 'Bad request: Missing `url`'

        url = request.GET['url'].split('\n')[0].strip()
        assert url != '', 'Bad request: Empty `url`'

        return CreateSaveWorkflow().run(
            request=request,
            account=request.user,
            url=url,
            force_post_save=True,
        )
    except Exception as exception:
        LOGGER.error(
            'Unhandled exception: %s',
            exception,
            exc_info=exception,
        )

    return render(
        request,
        'ui/errors/internal_server_error.html',
        # Returning 200 here to avoid browsers showing generic error pages.
        status=http.HTTPStatus.OK,
    )
