from django.shortcuts import redirect
from django.urls import reverse

class SlugRedirectMixin:
    """
    Mixin that handles redirects for old slugs.
    Requires the model to inherit from SluggedModel.
    """
    def get(self, request, *args, **kwargs):
        # Get the object using current or historical slug
        try:
            self.object = self.get_object()
            # Check if we used an old slug
            current_slug = kwargs.get(self.slug_url_kwarg)
            if current_slug != self.object.slug:
                # Get the URL pattern name from the view
                url_pattern = self.get_redirect_url_pattern()
                # Build kwargs for reverse()
                reverse_kwargs = self.get_redirect_url_kwargs()
                # Redirect to the current slug URL
                return redirect(
                    reverse(url_pattern, kwargs=reverse_kwargs),
                    permanent=True
                )
            return super().get(request, *args, **kwargs)
        except self.model.DoesNotExist:
            return super().get(request, *args, **kwargs)

    def get_redirect_url_pattern(self):
        """
        Get the URL pattern name for redirects.
        Should be overridden by subclasses.
        """
        raise NotImplementedError(
            "Subclasses must implement get_redirect_url_pattern()"
        )

    def get_redirect_url_kwargs(self):
        """
        Get the kwargs for reverse() when redirecting.
        Should be overridden by subclasses if they need custom kwargs.
        """
        return {self.slug_url_kwarg: self.object.slug}
