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

import logging
import uuid

import django.db
from django.db import models

from hotpocket_backend.apps.saves.models import Save
from hotpocket_common.db import postgres  # noqa: F401
from hotpocket_soa.dto.associations import AssociationsQuery

from .base import AssociationAdapter, SaveAdapter

LOGGER = logging.getLogger(__name__)


class PostgresSaveAdapter(SaveAdapter):
    ROW_LOCKED_MESSAGE = 'could not obtain lock on row in relation "saves_save"'

    def get_for_processing(self, *, pk: uuid.UUID) -> Save | None:
        try:
            return Save.active_objects.select_for_update(nowait=True).get(pk=pk)
        except django.db.utils.OperationalError as exception:
            if exception.args[0].startswith(self.ROW_LOCKED_MESSAGE) is True:
                LOGGER.info('Trying to process a locked save: pk=`%s`', pk)
                return None

            raise exception


class PostgresAssociationAdapter(AssociationAdapter):
    def get_search_term_filters(self, *, query: AssociationsQuery) -> list[models.Q]:
        result = [
            (
                models.Q(target__url__ilike=query.search)
                |
                models.Q(target_title__ilike=query.search)
                |
                models.Q(target__title__ilike=query.search)
                |
                models.Q(target_description__ilike=query.search)
                |
                models.Q(target__description__ilike=query.search)
            ),
        ]

        return result
