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

from django.contrib import messages
import django.db
from django.http import HttpRequest, HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

from hotpocket_backend.apps.accounts.types import PAccount
from hotpocket_soa.dto.associations import (
    AssociationOut,
    AssociationWithTargetOut,
)
from hotpocket_soa.dto.celery import AsyncResultOut
from hotpocket_soa.dto.saves import SaveIn, SaveOut

from .base import SaveWorkflow


class CreateSaveWorkflow(SaveWorkflow):
    def create_associate_and_process(self,
                                     account: PAccount,
                                     url: str,
                                     ) -> tuple[SaveOut, AssociationOut, AsyncResultOut | None]:
        with django.db.transaction.atomic():
            save = self.create(
                account.pk,
                SaveIn(url=url),
            )

            association = self.associate(account.pk, save)

        processing_result: AsyncResultOut | None = None
        if save.last_processed_at is None:
            processing_result = self.schedule_processing(save)

        return (save, association, processing_result)

    def run(self,
            *,
            request: HttpRequest,
            account: PAccount,
            url: str,
            force_post_save: bool = False,
            ) -> HttpResponse:
        save, association, processing_result = self.create_associate_and_process(
            account, url,
        )

        response = redirect(reverse('ui.associations.browse'))
        if force_post_save is True or save.is_netloc_banned is True:
            response = redirect(reverse(
                'ui.associations.post_save',
                args=(association.pk,),
            ))
        else:
            messages.add_message(
                request,
                messages.SUCCESS,
                _('Your link has been saved!'),
            )

        response.headers['X-HotPocket-Testing-Save-PK'] = save.pk
        response.headers['X-HotPocket-Testing-Association-PK'] = association.pk

        return response

    def run_rpc(self,
                *,
                request: HttpRequest,
                account: PAccount,
                url: str,
                ) -> AssociationWithTargetOut:
        save, association, processing_result = self.create_associate_and_process(
            account, url,
        )

        result = AssociationWithTargetOut.from_association_save(
            association=association,
            save=save,
        )

        return result
