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

import logging
import uuid

from django.core.exceptions import PermissionDenied
from django.http import Http404

from hotpocket_soa.dto.associations import (
    AssociationOut,
    AssociationWithTargetOut,
)
from hotpocket_soa.services import AssociationsService

LOGGER = logging.getLogger(__name__)


class UIAssociationsService:
    def __init__(self):
        self.associations_service = AssociationsService()

    def get_or_404(self,
                   *,
                   account_uuid: uuid.UUID | None,
                   pk: uuid.UUID,
                   with_target: bool = False,
                   allow_archived: bool = False,
                   ) -> AssociationOut | AssociationWithTargetOut:
        try:
            return AssociationsService().get(
                account_uuid=account_uuid,
                pk=pk,
                with_target=True,
                allow_archived=allow_archived,
            )
        except AssociationsService.NotFound as exception:
            LOGGER.error(
                'Association not found: account_uuid=`%s` pk=`%s`',
                account_uuid,
                pk,
                exc_info=exception,
            )
            raise Http404()
        except AssociationsService.AccessDenied as exception:
            LOGGER.error(
                'Association access denied: account_uuid=`%s` pk=`%s`',
                account_uuid,
                pk,
                exc_info=exception,
            )
            raise PermissionDenied()

    def star_on_unstar(self,
                       *,
                       association: AssociationOut,
                       star: bool,
                       ) -> AssociationWithTargetOut:
        if star is True:
            _ = AssociationsService().star(association=association)
        else:
            _ = AssociationsService().unstar(association=association)

        return AssociationsService().get(  # type: ignore[return-value]
            account_uuid=association.account_uuid,
            pk=association.pk,
            with_target=True,
        )
