from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.models import AbstractUser
from django.db import models

class ClientPermission(models.Model):
    codename = models.CharField(max_length=100, default='')
    name = models.CharField(max_length=255, default='')

    class Meta:
        managed = True
        default_permissions = ()
        permissions = (
            ('can_view_booking', 'Can view booking'),
            ('can_manage_booking', 'Can book container'),

            ('can_view_preinfo', 'Can view preinfo'),
            ('can_manage_preinfo', 'Can manage preinfo'),

            ('can_view_payment', 'Can view payment'),
            ('can_manage_payment', 'Can manage payment'),

            ('can_manage_company_users', 'Can manage company users'),
        )


    def __str__(self):
        return self.name

class EmployeePermission(models.Model):
    codename = models.CharField(max_length=100, default='')
    name = models.CharField(max_length=255, default='')

    class Meta:
        managed = True
        default_permissions = ()
        permissions = (
            ('can_manage_containers', 'Can manage containers'),
            ('can_view_reports', 'Can view reports'),
            ('can_handle_operations', 'Can handle operations'),
        )

    def __str__(self):
        return self.name


class CustomUserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError('Users must have an email address')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)
        extra_fields.setdefault('user_type', 'AD')  # Set user_type to admin

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self.create_user(email, password, **extra_fields)


class DepotUser(AbstractUser):

    class UserType(models.TextChoices):
        BARRIER_STAFF = 'BS', 'Barrier Staff'
        COMPANY_ADMIN = 'CA', 'Company Admin'
        EMPLOYEE = 'EM', 'Employee'
        CLIENT = 'CL', 'Client',
        ADMIN = 'AD', 'Admin'

    objects = CustomUserManager()

    user_type = models.CharField(
        max_length=2,
        choices=UserType.choices,
        default=UserType.CLIENT
    )

    phone_number = models.CharField(max_length=15, blank=True, null=True)
    email = models.EmailField(unique=True, blank=False, null=False)
    company = models.ForeignKey(
        'common.CompanyModel',
        on_delete=models.CASCADE,
        related_name='user_lines',
        blank=True,
        null=True
    )
    line = models.ForeignKey(
        'common.LinesModel',
        on_delete=models.CASCADE,
        related_name='user_lines',
        blank=True,
        null=True
    )

    company_permissions = models.ManyToManyField('ClientPermission')
    employee_permissions = models.ManyToManyField('EmployeePermission', blank=True)

    def has_company_perm(self, perm_codename):
        if self.is_superuser:
            return True
        return self.company_permissions.filter(codename=perm_codename).exists()

    def has_employee_perm(self, perm_codename):
        if self.is_superuser:
            return True
        return self.employee_permissions.filter(codename=perm_codename).exists()