from django.conf import settings
from django.contrib.postgres.search import (
    SearchQuery,
    SearchRank,
    SearchVector,
    TrigramSimilarity,
)
from django.db import models
from django.utils.translation import gettext_lazy as _


class NummiQuerySet(models.QuerySet):
    main_field = "name"
    fields = dict()

    def search(self, search):
        return (
            self.annotate(
                rank=SearchRank(
                    sum(
                        (
                            SearchVector(field, weight=weight)
                            for field, weight in self.fields.items()
                        ),
                        start=SearchVector(self.main_field, weight="A"),
                    ),
                    SearchQuery(search, search_type="websearch"),
                ),
                similarity=TrigramSimilarity(self.main_field, search),
            )
            .filter(models.Q(rank__gte=0.1) | models.Q(similarity__gte=0.3))
            .order_by("-rank")
        )


class NummiModel(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        verbose_name=_("User"),
        editable=False,
    )
    objects = NummiQuerySet.as_manager()

    class Meta:
        abstract = True
