"""
Author: Michel Peltriaux
Created on: 14.12.25

"""
from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render

from intervention.models import Intervention
from konova.contexts import BaseContext
from konova.forms import SimpleGeomForm
from konova.settings import DEFAULT_GROUP, ZB_GROUP, ETS_GROUP
from konova.sub_settings.context_settings import TAB_TITLE_IDENTIFIER
from konova.utils.message_templates import DATA_CHECKED_PREVIOUSLY_TEMPLATE, DO_NOT_FORGET_TO_SHARE
from konova.views.detail import AbstractDetailView


class DetailInterventionView(AbstractDetailView):
    _TEMPLATE = "intervention/detail/view.html"

    def get(self, request, id: str, *args, **kwargs) -> HttpResponse:
        # Fetch data, filter out deleted related data
        intervention = get_object_or_404(
            Intervention.objects.select_related(
                "geometry",
                "legal",
                "responsible",
            ).prefetch_related(
                "legal__revocations",
            ),
            id=id,
            deleted=None
        )
        compensations = intervention.compensations.filter(
            deleted=None,
        )
        _user = request.user
        is_data_shared = intervention.is_shared_with(user=_user)

        geom_form = SimpleGeomForm(
            instance=intervention,
        )
        last_checked = intervention.get_last_checked_action()
        last_checked_tooltip = ""
        if last_checked:
            last_checked_tooltip = DATA_CHECKED_PREVIOUSLY_TEMPLATE.format(
                last_checked.get_timestamp_str_formatted(),
                last_checked.user
            )

        has_payment_without_document = intervention.payments.exists() and not intervention.get_documents()[1].exists()

        requesting_user_is_only_shared_user = intervention.is_only_shared_with(_user)
        if requesting_user_is_only_shared_user:
            messages.info(
                request,
                DO_NOT_FORGET_TO_SHARE
            )

        context = {
            "obj": intervention,
            "last_checked": last_checked,
            "last_checked_tooltip": last_checked_tooltip,
            "compensations": compensations,
            "is_entry_shared": is_data_shared,
            "geom_form": geom_form,
            "is_default_member": _user.in_group(DEFAULT_GROUP),
            "is_zb_member": _user.in_group(ZB_GROUP),
            "is_ets_member": _user.in_group(ETS_GROUP),
            "LANIS_LINK": intervention.get_LANIS_link(),
            "has_payment_without_document": has_payment_without_document,
            TAB_TITLE_IDENTIFIER: f"{intervention.identifier} - {intervention.title}",
        }

        request = intervention.set_status_messages(request)

        context = BaseContext(request, context).context
        return render(request, self._TEMPLATE, context)
