from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse

from tickets.models import Attachment
from tickets.utils import remove_attachment_file


@login_required
def remove_attachment(request, attachment_id):
    if request.method == "POST":
        attachment = get_object_or_404(Attachment, pk=attachment_id)

        # Permissions
        is_admin_or_staff = request.user.is_superuser or request.user.is_staff
        is_attachment_accessible = (
            attachment.added_by == request.user or
            attachment.ticket.created_by == request.user and (
                attachment.ticket.assigned_to == request.user or
                attachment.ticket.list.group in request.user.groups.all()
            )
        )

        if not (is_admin_or_staff or is_attachment_accessible):
            raise PermissionDenied

        if remove_attachment_file(attachment.id):
            messages.success(request, f"The attachment has been successfully deleted.")
        else:
            messages.error(request, f"Sorry, there was a problem deleting attachment.")

        return redirect(reverse("tickets:ticket_detail", kwargs={"pk": attachment.ticket.pk}))

    else:
        raise PermissionDenied
