from django.contrib.auth.models import Permission
from django.db import models


# Create your models here.
class UserPermission(models.Model):
    class Meta:
        indexes = [
            models.Index(fields=['user', 'perm', 'restricted_object'], name='idx_userperm_user_perm_obj'),
        ]
        constraints = [
            models.UniqueConstraint(
                fields=['user', 'perm', 'restricted_object', 'source'],
                name='uniq_userperm_user_perm_obj_src',
            ),
        ]

    perm = models.ForeignKey(Permission,
                             on_delete=models.PROTECT,
                             related_name='user_permissions',
                             null=False)
    
    restricted_object = models.ForeignKey('topdownrbac.RestrictedObject',
                                          on_delete=models.PROTECT,
                                          related_name= 'user_permissions',
                                          null=False)
    user = models.ForeignKey('topdownrbac.UserSubject',
                             on_delete=models.PROTECT,
                             related_name= 'permissions',
                             null=False)

    source = models.ForeignKey('topdownrbac.RoleBinding',
                               on_delete=models.PROTECT,
                               null=False)

    def __str__(self):
        return self.name