from typing import Type

from engine.payments.gateways import AbstractGateway
from engine.payments.models import Gateway
from evibes.utils.misc import create_object


def get_gateways_integrations(name: str | None = None) -> list[Type[AbstractGateway]]:
    gateways_integrations: list[Type[AbstractGateway]] = []
    gateways = (
        Gateway.objects.filter(is_active=True, name=name)
        if name
        else Gateway.objects.filter(is_active=True)
    )
    for gateway in gateways:
        if gateway.integration_path:
            module_name = ".".join(gateway.integration_path.split(".")[:-1])
            class_name = gateway.integration_path.split(".")[-1]
            gateways_integrations.append(create_object(module_name, class_name))
    return gateways_integrations


def get_limits() -> tuple[float, float]:
    from django.db.models import Max, Min

    qs = Gateway.objects.can_be_used().filter(can_be_used=True)

    if not qs.exists():
        return 0.0, 0.0

    agg = qs.aggregate(
        min_limit=Min("minimum_transaction_amount"),
        max_limit=Max("maximum_transaction_amount"),
    )

    min_limit = float(agg.get("min_limit") or 0.0)
    max_limit = float(agg.get("max_limit") or 0.0)
    return min_limit, max_limit
