from decimal import Decimal

from django.db import models
from django.db.models.functions import Coalesce

from ocyan.plugin.oscar_catalogue.catalogue import abstract_models as ocyan


class AbstractProduct(ocyan.AbstractProduct):
    @property
    def variants_ordered_by_price(self):
        return (
            self.children.filter(is_public=True)
            .annotate(
                lowest_price=Coalesce(
                    models.Avg("stockrecords__price"),
                    models.Value(
                        Decimal(999999999)
                    ),  # put children with no stock at the end
                )
            )
            .order_by("lowest_price", "-priority")
        )

    @property
    def variants_ordered_for_admin(self):
        return (
            self.children.all()
            .annotate(
                lowest_price=Coalesce(
                    models.Avg("stockrecords__price"),
                    models.Value(
                        Decimal(999999999)
                    ),  # put children with no stock at the end
                )
            )
            .order_by("lowest_price", "-priority")
        )

    class Meta(ocyan.AbstractProduct.Meta):
        abstract = True
