import graphene
from django.db.models import QuerySet
from graphene import relay
from graphene.types.generic import GenericScalar
from graphene_django import DjangoObjectType

from payments.models import Balance, Transaction


class TransactionType(DjangoObjectType):
    process = GenericScalar()

    def resolve_process(self: Transaction, info) -> dict:
        if self.balance is not None:
            if info.context.user == self.balance.user:
                return self.process
        return {}

    class Meta:
        model = Transaction
        exclude = ("balance",)
        interfaces = (relay.Node,)
        filter_fields = ["is_active"]


class BalanceType(DjangoObjectType):
    transactions = graphene.List(lambda: TransactionType)

    class Meta:
        model = Balance
        fields = "__all__"
        interfaces = (relay.Node,)
        filter_fields = ["is_active"]

    def resolve_transactions(self: Balance, info) -> list | QuerySet:
        if info.context.user == self.user:
            # noinspection Mypy
            return self.transactions.all() or []
        return []
