from django.contrib.auth.decorators import login_required
from django.db.models import Q, F
from django.shortcuts import render
from django.db.models.functions import Concat

from tickets.models import Ticket


@login_required
def search(request):
    found_tickets = None
    query_string = ""
    
    if request.GET:
        if ("search" in request.GET) and request.GET["search"].strip():
            query_string = request.GET["search"]

            found_tickets = Ticket.objects.all()
            if not request.user.is_superuser:
                found_tickets = found_tickets.filter(
                    Q(ticket_list__group__in=request.user.groups.all())
                    | Q(assigned_to=request.user)
                )
            
            found_tickets = found_tickets.annotate(created_by_username=F("created_by__username"))
            found_tickets = found_tickets.annotate(assigned_to_username=F("assigned_to__username"))

            found_tickets = found_tickets.filter(
                Q(title__icontains=query_string)
                | Q(ticket_list__name__icontains=query_string)
                | Q(note__icontains=query_string)
                | Q(created_by_username__icontains=query_string)
                | Q(assigned_to_username__icontains=query_string)
                | Q(status__icontains=query_string)
            )

            found_tickets = found_tickets.select_related("ticket_list")
            found_tickets = found_tickets.order_by("-priority")

    context = {
        "query_string": query_string,
        "found_tickets": found_tickets
    }

    return render(request, "tickets/search.html", context)
