from django.db import models

class Rank(models.Model):
    opportunity_bundle = models.ForeignKey(
        'schemes.OpportunityBundle',
        related_name='ranks',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    level_number = models.PositiveIntegerField()
    name = models.CharField(max_length=100)
    badge_image = models.ImageField(upload_to='rank_badges/', blank=True, null=True)
    badge_icon = models.CharField(max_length=100, blank=True, null=True, help_text='Optional icon class or name')

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["level_number"],
                condition=models.Q(opportunity_bundle__isnull=True),
                name="uniq_global_rank_per_level",
            ),
            models.UniqueConstraint(
                fields=["opportunity_bundle", "level_number"],
                condition=models.Q(opportunity_bundle__isnull=False),
                name="uniq_opportunity_bundle_rank_per_level",
            ),
        ]
        ordering = ["level_number", "opportunity_bundle_id"]

    def __str__(self):
        bundle_name = self.opportunity_bundle.name if self.opportunity_bundle else "All Opportunity Bundles"
        return f"{bundle_name} - Level {self.level_number}: {self.name}"
