from django.db import models
from django.conf import settings
from django.utils import timezone
import secrets
import time


def uuid7() -> str:
    """Generate a UUID v7 (time-ordered UUID)."""
    nanoseconds = time.time_ns()
    uuid_int = (nanoseconds << 16) | secrets.randbits(48)
    return f"{uuid_int:032x}"


class Company(models.Model):
    """Company/organization records."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    name = models.CharField(max_length=255)
    abbreviation = models.CharField(max_length=20, blank=True, db_index=True,
        help_text="Short code / acronym, e.g. WHO, UNICEF.")
    slug = models.SlugField(max_length=255, unique=True, blank=True, null=True)
    legal_name = models.CharField(max_length=255, blank=True)
    company_type = models.CharField(max_length=20, choices=[
        ("organization", "Organization"),
        ("donor", "Donor"),
    ], default="organization", db_index=True)
    donor_category = models.CharField(max_length=20, choices=[
        ("regular", "Regular"),
        ("project", "Project"),
    ], default="regular", db_index=True, blank=True,
       help_text="Only meaningful when company_type='donor'. Project = linked via ProjectFund.")
    industry = models.CharField(max_length=100, blank=True)
    website = models.URLField(blank=True)
    email = models.EmailField(blank=True)
    phone = models.CharField(max_length=20, blank=True)
    address = models.TextField(blank=True)
    city = models.CharField(max_length=100, blank=True)
    country = models.CharField(max_length=100, blank=True)
    tax_id = models.CharField(max_length=50, blank=True)
    pic = models.CharField(max_length=255, blank=True, help_text="Person in charge / primary contact name.")
    pic_title = models.CharField(max_length=255, blank=True, help_text="PIC position / job title.")
    logo = models.ImageField(upload_to="company_logos/", null=True, blank=True)
    description = models.TextField(blank=True)
    notes = models.TextField(blank=True)
    tags = models.JSONField(default=list)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "companies"
        ordering = ["name"]

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug and self.name:
            self.slug = self.name.lower().replace(" ", "-")
        super().save(*args, **kwargs)


class OrgProfile(models.Model):
    """Singleton record for the organization running this CRM."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    name = models.CharField(max_length=255, default="My Organization")
    legal_name = models.CharField(max_length=255, blank=True)
    tagline = models.CharField(max_length=255, blank=True)
    logo = models.ImageField(upload_to="company_logos/", null=True, blank=True)
    email = models.EmailField(blank=True)
    phone = models.CharField(max_length=30, blank=True)
    website = models.URLField(blank=True)
    address = models.TextField(blank=True)
    city = models.CharField(max_length=100, blank=True)
    country = models.CharField(max_length=100, blank=True)
    latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    tax_id = models.CharField(max_length=50, blank=True)
    description = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "org_profile"

    def __str__(self):
        return self.name


class Director(models.Model):
    """Board / executive director records — always linked to an Employee."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    employee = models.OneToOneField(
        "hr.Employee", on_delete=models.CASCADE, related_name="director_role",
    )
    title = models.CharField(max_length=255, blank=True, help_text="Director role, e.g. CEO, Board Chair")
    bio = models.TextField(blank=True, help_text="Director-specific bio shown on org profile")
    order = models.PositiveIntegerField(default=0)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "org_directors"
        ordering = ["order", "id"]

    def __str__(self):
        emp_name = self.employee.user.get_full_name() if self.employee_id else "?"
        return f"{emp_name} ({self.title})" if self.title else emp_name


class Department(models.Model):
    """Internal departments within the organization."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    name = models.CharField(max_length=255, unique=True)
    code = models.CharField(max_length=20, blank=True, help_text="Short code, e.g. POL, ECO")
    description = models.TextField(blank=True)
    parent = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="children")
    head = models.ForeignKey("hr.Employee", on_delete=models.SET_NULL, null=True, blank=True, related_name="led_departments")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "org_departments"
        ordering = ["name"]

    def __str__(self):
        return self.name