# -*- coding: utf-8 -*-
"""
Adtlas Accounts Models

This module contains the custom user authentication models for the Adtlas DAI Management System.
It implements a flexible role-based permission system with dynamic roles and comprehensive
user management capabilities.

Features:
    - Custom User model with email-based authentication
    - Dynamic Role system with hierarchical permissions
    - User profiles with detailed information
    - Activity tracking and session management
    - Department-based organization structure

Author: Adtlas Development Team
Version: 2.0.0
Last Updated: 2025-07-08
"""

import uuid 
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.core.validators import RegexValidator
from django.utils.translation import gettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import AbstractUser, PermissionsMixin, Permission

from apps.accounts.managers import UserManager
from apps.common.models import BaseModel, TimeStampedModel


class Department(BaseModel):
    """
    Department model for organizing users within the company structure.
    Departments can have hierarchical relationships and specific permissions.
    """

    name = models.CharField(
        max_length=100,
        unique=True,
        help_text="Department name (e.g., 'Marketing', 'Sales', 'IT')"
    )

    code = models.CharField(
        max_length=20,
        unique=True,
        validators=[RegexValidator(r"^[A-Z]{2,20}$", "Code must be uppercase letters only")],
        help_text="Department code (e.g., 'MKT', 'SALES', 'IT')"
    )

    description = models.TextField(
        blank=True,
        help_text="Detailed description of the department's responsibilities"
    )

    parent = models.ForeignKey(
        "self",
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name="children",
        help_text="Parent department for hierarchical structure"
    )

    head = models.ForeignKey(
        "accounts.User",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="headed_departments",
        help_text="Department head/manager"
    )

    is_active = models.BooleanField(
        default=True,
        help_text="Whether this department is currently active"
    )

    class Meta:
        db_table = "accounts_departments"
        ordering = ["name"]
        verbose_name = "Department"
        verbose_name_plural = "Departments"

    def __str__(self):
        return f"{self.name} ({self.code})"

    def get_all_children(self):
        """Get all child departments recursively"""
        children = list(self.children.all())
        for child in self.children.all():
            children.extend(child.get_all_children())
        return children

    def get_all_users(self):
        """Get all users in this department and its children"""
        from django.db.models import Q
        departments = [self] + self.get_all_children()
        return User.objects.filter(profile__department__in=departments)


 
        
class Profile(BaseModel): 
    """
    Extended user profile model for additional user information.
    
    This model stores additional user data that doesn"t belong
    in the core User model, following the principle of separation of concerns.
    """
 
    
    department = models.ForeignKey(
        Department,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="users",
        help_text="User department within the company"
    )

    employee_id = models.CharField(
        max_length=50,
        blank=True,
        unique=True,
        null=True,
        help_text="Employee ID or staff number"
    )

    hire_date = models.DateField(
        null=True,
        blank=True,
        help_text="Date when the user was hired"
    )

    manager = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="subordinates",
        help_text="User's direct manager"
    )
    

 
    
    # Contact Information
    # Address information
    address_line1 = models.CharField(
        _("Address Line 1"),
        max_length=255,
        blank=True,
        help_text=_("Street address")
    )
    
    address_line2 = models.CharField(
        _("Address Line 2"),
        max_length=255,
        blank=True,
        help_text=_("Apartment, suite, etc.")
    )
    
    city = models.CharField(
        _("City"),
        max_length=100,
        blank=True,
        help_text=_("City")
    )
    
    state = models.CharField(
        _("State/Province"),
        max_length=100,
        blank=True,
        help_text=_("State or province")
    )
    
    postal_code = models.CharField(
        _("Postal Code"),
        max_length=20,
        blank=True,
        help_text=_("ZIP or postal code")
    )
    
    country = models.CharField(
        _("Country"),
        max_length=100,
        blank=True,
        help_text=_("Country")
    )

    emergency_contact_name = models.CharField(
        max_length=100,
        blank=True,
        help_text="Emergency contact person name"
    )

    emergency_contact_phone = models.CharField(
        max_length=20,
        blank=True,
        help_text="Emergency contact phone number"
    )
 
 
    def get_absolute_url(self):
        """Return the absolute URL for the user profile."""
        return reverse("accounts:profile", kwargs={"pk": self.user.pk})






