
import graphene
from django.utils.translation import gettext_lazy as _
from typing import Type
from django_relay_endpoint.configurators.object_types import DjangoClientIDMutation
from graphql_relay.node.node import from_global_id

def configure_delete_mutation(
        abstract_mutation_type: Type[DjangoClientIDMutation], 
        conventional_name: str,
        success_keyword: str = None,
    ) ->  Type[DjangoClientIDMutation]:
    """
    Configures a DjangoClientIDMutation class named <conventional_name>DeleteMutation.
    The mutation extends abstract_mutation_type and implements 'mutate_and_get_payload' method, as well as Input class with id field.


    Args:
        abstract_mutation_type (Type[DjangoClientIDMutation]): 
        DjangoClientIDMutation abstract class generated by Abstract_mutation_class_configurator

        conventional_name (str): 
        Conventional name prefiexed to the returned DjangoClientIDMutation class name

    Returns:
        Type[DjangoClientIDMutation]: The DjangoClientIDMutation class implementation
    """

    @classmethod
    def mutate_and_get_payload(cls, root, info, *args, **kwargs):
        """
        The `mutate_and_get_payload` classmethod, which gets id using `graphql_relay.node.node.from_global_id`.
        See <https://docs.graphene-python.org/projects/django/en/latest/mutations/#relay> for `mutate_and_get_payload`.
        """

        client_mutation_id = kwargs.get("client_mutation_id", None) 

        # use from_global_id inside mutate_and_get_payload to ensure it is similar to graphene_django.DjangoObjectType implementation
        id = from_global_id(kwargs.get("id")).id
        
        instance = cls.get_node(info, id)
        instance.delete()
        mutation_kwargs = {
            success_keyword or "success": True,
            'client_mutation_id': client_mutation_id
        }
        return cls(**mutation_kwargs)
    
    # declare a Input class which accepts id only
    class Input:
        id = graphene.ID(required=True)

    # configure the DeleteMutation
    mutation = type(f'{conventional_name}DeleteMutation', (abstract_mutation_type,), {
        'Input': Input,
        'mutate_and_get_payload': mutate_and_get_payload,
    })

    return mutation
