from django.db import models


class Menu(models.Model):
    """A sidebar menu item. Parents have permission_code=NULL and are shown only
    when at least one of their children is visible to the user. Children carry a
    permission_code ('<app_label>.<codename>') and are shown only when the user
    holds that permission (admins see everything)."""

    name = models.CharField(max_length=100)
    route = models.CharField(max_length=200, blank=True, default="")
    icon = models.CharField(max_length=100, blank=True, default="")
    parent = models.ForeignKey(
        "self", null=True, blank=True, on_delete=models.CASCADE, related_name="children"
    )
    sort_order = models.PositiveIntegerField(default=0)
    permission_code = models.CharField(
        max_length=100, blank=True, default="",
        help_text="app_label.codename that unlocks this item. Blank = always shown (e.g. a parent).",
    )
    is_active = models.BooleanField(default=True)
    admin_only = models.BooleanField(default=False, help_text="If true, only ADMIN role users can see this item.")

    class Meta:
        db_table = "menus"
        ordering = ["sort_order", "id"]

    def __str__(self):
        return self.name
